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,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/Tools/ExternalAccess/FSharp/xlf/ExternalAccessFSharpResources.ko.xlf | ๏ปฟ<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../ExternalAccessFSharpResources.resx">
<body>
<trans-unit id="AddAssemblyReference">
<source>Add an assembly reference to '{0}'</source>
<target state="translated">'{0}'์ ์ด์
๋ธ๋ฆฌ ์ฐธ์กฐ ์ถ๊ฐ</target>
<note />
</trans-unit>
<trans-unit id="AddNewKeyword">
<source>Add 'new' keyword</source>
<target state="translated">'new' ํค์๋ ์ถ๊ฐ</target>
<note />
</trans-unit>
<trans-unit id="AddProjectReference">
<source>Add a project reference to '{0}'</source>
<target state="translated">'{0}'์ ํ๋ก์ ํธ ์ฐธ์กฐ ์ถ๊ฐ</target>
<note />
</trans-unit>
<trans-unit id="CannotDetermineSymbol">
<source>Cannot determine the symbol under the caret</source>
<target state="translated">์บ๋ฟ์์ ๊ธฐํธ๋ฅผ ํ์ธํ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
<trans-unit id="CannotNavigateUnknown">
<source>Cannot navigate to the requested location</source>
<target state="translated">์์ฒญํ ์์น๋ก ์ด๋ํ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
<trans-unit id="ExceptionsHeader">
<source>Exceptions:</source>
<target state="translated">์์ธ:</target>
<note />
</trans-unit>
<trans-unit id="FSharpDisposablesClassificationType">
<source>F# Disposable Types</source>
<target state="translated">F# ์ญ์ ๊ฐ๋ฅํ ํ์</target>
<note />
</trans-unit>
<trans-unit id="FSharpFunctionsOrMethodsClassificationType">
<source>F# Functions / Methods</source>
<target state="translated">F# ํจ์/๋ฉ์๋</target>
<note />
</trans-unit>
<trans-unit id="FSharpMutableVarsClassificationType">
<source>F# Mutable Variables / Reference Cells</source>
<target state="translated">F# ๋ณ๊ฒฝ ๊ฐ๋ฅํ ๋ณ์/์ฐธ์กฐ ์
</target>
<note />
</trans-unit>
<trans-unit id="FSharpPrintfFormatClassificationType">
<source>F# Printf Format</source>
<target state="translated">F# Printf ํ์</target>
<note />
</trans-unit>
<trans-unit id="FSharpPropertiesClassificationType">
<source>F# Properties</source>
<target state="translated">F# ์์ฑ</target>
<note />
</trans-unit>
<trans-unit id="GenericParametersHeader">
<source>Generic parameters:</source>
<target state="translated">์ ๋ค๋ฆญ ๋งค๊ฐ ๋ณ์:</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterface">
<source>Implement interface</source>
<target state="translated">์ธํฐํ์ด์ค ๊ตฌํ</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterfaceWithoutTypeAnnotation">
<source>Implement interface without type annotation</source>
<target state="translated">ํ์ ์ฃผ์ ์์ด ์ธํฐํ์ด์ค ๊ตฌํ</target>
<note />
</trans-unit>
<trans-unit id="LocatingSymbol">
<source>Locating the symbol under the caret...</source>
<target state="translated">์บ๋ฟ์์ ๊ธฐํธ๋ฅผ ์ฐพ๋ ์ค...</target>
<note />
</trans-unit>
<trans-unit id="NameCanBeSimplified">
<source>Name can be simplified.</source>
<target state="translated">์ด๋ฆ์ ๊ฐ๋จํ๊ฒ ์ค์ผ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
<trans-unit id="NavigateToFailed">
<source>Navigate to symbol failed: {0}</source>
<target state="translated">๊ธฐํธ๋ก ์ด๋ํ์ง ๋ชปํจ: {0}</target>
<note />
</trans-unit>
<trans-unit id="NavigatingTo">
<source>Navigating to symbol...</source>
<target state="translated">๊ธฐํธ๋ก ์ด๋ํ๋ ์ค...</target>
<note />
</trans-unit>
<trans-unit id="PrefixValueNameWithUnderscore">
<source>Prefix '{0}' with underscore</source>
<target state="translated">'{0}' ์์ ๋ฐ์ค ๋ถ์ด๊ธฐ</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnusedOpens">
<source>Remove unused open declarations</source>
<target state="translated">์ฌ์ฉ๋์ง ์๋ ์ด๋ ค ์๋ ์ ์ธ ์ ๊ฑฐ</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToDoubleUnderscore">
<source>Rename '{0}' to '__'</source>
<target state="translated">'{0}'์์ '__'๋ก ์ด๋ฆ ๋ฐ๊พธ๊ธฐ</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToUnderscore">
<source>Rename '{0}' to '_'</source>
<target state="translated">'{0}'์์ '_'๋ก ์ด๋ฆ ๋ฐ๊พธ๊ธฐ</target>
<note />
</trans-unit>
<trans-unit id="SimplifyName">
<source>Simplify name</source>
<target state="translated">์ด๋ฆ ๋จ์ํ</target>
<note />
</trans-unit>
<trans-unit id="TheValueIsUnused">
<source>The value is unused</source>
<target state="translated">๊ฐ์ด ์ฌ์ฉ๋์ง ์์</target>
<note />
</trans-unit>
<trans-unit id="UnusedOpens">
<source>Open declaration can be removed.</source>
<target state="translated">์ด๋ ค ์๋ ์ ์ธ์ ์ ๊ฑฐํ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | ๏ปฟ<?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="ko" original="../ExternalAccessFSharpResources.resx">
<body>
<trans-unit id="AddAssemblyReference">
<source>Add an assembly reference to '{0}'</source>
<target state="translated">'{0}'์ ์ด์
๋ธ๋ฆฌ ์ฐธ์กฐ ์ถ๊ฐ</target>
<note />
</trans-unit>
<trans-unit id="AddNewKeyword">
<source>Add 'new' keyword</source>
<target state="translated">'new' ํค์๋ ์ถ๊ฐ</target>
<note />
</trans-unit>
<trans-unit id="AddProjectReference">
<source>Add a project reference to '{0}'</source>
<target state="translated">'{0}'์ ํ๋ก์ ํธ ์ฐธ์กฐ ์ถ๊ฐ</target>
<note />
</trans-unit>
<trans-unit id="CannotDetermineSymbol">
<source>Cannot determine the symbol under the caret</source>
<target state="translated">์บ๋ฟ์์ ๊ธฐํธ๋ฅผ ํ์ธํ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
<trans-unit id="CannotNavigateUnknown">
<source>Cannot navigate to the requested location</source>
<target state="translated">์์ฒญํ ์์น๋ก ์ด๋ํ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
<trans-unit id="ExceptionsHeader">
<source>Exceptions:</source>
<target state="translated">์์ธ:</target>
<note />
</trans-unit>
<trans-unit id="FSharpDisposablesClassificationType">
<source>F# Disposable Types</source>
<target state="translated">F# ์ญ์ ๊ฐ๋ฅํ ํ์</target>
<note />
</trans-unit>
<trans-unit id="FSharpFunctionsOrMethodsClassificationType">
<source>F# Functions / Methods</source>
<target state="translated">F# ํจ์/๋ฉ์๋</target>
<note />
</trans-unit>
<trans-unit id="FSharpMutableVarsClassificationType">
<source>F# Mutable Variables / Reference Cells</source>
<target state="translated">F# ๋ณ๊ฒฝ ๊ฐ๋ฅํ ๋ณ์/์ฐธ์กฐ ์
</target>
<note />
</trans-unit>
<trans-unit id="FSharpPrintfFormatClassificationType">
<source>F# Printf Format</source>
<target state="translated">F# Printf ํ์</target>
<note />
</trans-unit>
<trans-unit id="FSharpPropertiesClassificationType">
<source>F# Properties</source>
<target state="translated">F# ์์ฑ</target>
<note />
</trans-unit>
<trans-unit id="GenericParametersHeader">
<source>Generic parameters:</source>
<target state="translated">์ ๋ค๋ฆญ ๋งค๊ฐ ๋ณ์:</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterface">
<source>Implement interface</source>
<target state="translated">์ธํฐํ์ด์ค ๊ตฌํ</target>
<note />
</trans-unit>
<trans-unit id="ImplementInterfaceWithoutTypeAnnotation">
<source>Implement interface without type annotation</source>
<target state="translated">ํ์ ์ฃผ์ ์์ด ์ธํฐํ์ด์ค ๊ตฌํ</target>
<note />
</trans-unit>
<trans-unit id="LocatingSymbol">
<source>Locating the symbol under the caret...</source>
<target state="translated">์บ๋ฟ์์ ๊ธฐํธ๋ฅผ ์ฐพ๋ ์ค...</target>
<note />
</trans-unit>
<trans-unit id="NameCanBeSimplified">
<source>Name can be simplified.</source>
<target state="translated">์ด๋ฆ์ ๊ฐ๋จํ๊ฒ ์ค์ผ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
<trans-unit id="NavigateToFailed">
<source>Navigate to symbol failed: {0}</source>
<target state="translated">๊ธฐํธ๋ก ์ด๋ํ์ง ๋ชปํจ: {0}</target>
<note />
</trans-unit>
<trans-unit id="NavigatingTo">
<source>Navigating to symbol...</source>
<target state="translated">๊ธฐํธ๋ก ์ด๋ํ๋ ์ค...</target>
<note />
</trans-unit>
<trans-unit id="PrefixValueNameWithUnderscore">
<source>Prefix '{0}' with underscore</source>
<target state="translated">'{0}' ์์ ๋ฐ์ค ๋ถ์ด๊ธฐ</target>
<note />
</trans-unit>
<trans-unit id="RemoveUnusedOpens">
<source>Remove unused open declarations</source>
<target state="translated">์ฌ์ฉ๋์ง ์๋ ์ด๋ ค ์๋ ์ ์ธ ์ ๊ฑฐ</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToDoubleUnderscore">
<source>Rename '{0}' to '__'</source>
<target state="translated">'{0}'์์ '__'๋ก ์ด๋ฆ ๋ฐ๊พธ๊ธฐ</target>
<note />
</trans-unit>
<trans-unit id="RenameValueToUnderscore">
<source>Rename '{0}' to '_'</source>
<target state="translated">'{0}'์์ '_'๋ก ์ด๋ฆ ๋ฐ๊พธ๊ธฐ</target>
<note />
</trans-unit>
<trans-unit id="SimplifyName">
<source>Simplify name</source>
<target state="translated">์ด๋ฆ ๋จ์ํ</target>
<note />
</trans-unit>
<trans-unit id="TheValueIsUnused">
<source>The value is unused</source>
<target state="translated">๊ฐ์ด ์ฌ์ฉ๋์ง ์์</target>
<note />
</trans-unit>
<trans-unit id="UnusedOpens">
<source>Open declaration can be removed.</source>
<target state="translated">์ด๋ ค ์๋ ์ ์ธ์ ์ ๊ฑฐํ ์ ์์ต๋๋ค.</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/FlowAnalysis/LValueFlowCaptureProvider.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
#if DEBUG
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Helper class to detect <see cref="IFlowCaptureOperation"/>s that are l-value captures.
/// L-value captures are essentially captures of a symbol's location/address.
/// Corresponding <see cref="IFlowCaptureReferenceOperation"/>s which share the same
/// <see cref="CaptureId"/> as this flow capture, dereferences and writes to this location
/// subsequently in the flow graph.
/// For example, consider the below code:
/// a[i] = x ?? a[j];
/// The control flow graph contains an initial flow capture of "a[i]" to capture the l-value
/// of this array element:
/// FC0 (a[i])
/// Then it evaluates the right hand side, which can have different
/// values on different control flow paths, and the resultant value is then written
/// to the captured location:
/// FCR0 = result
/// </summary>
/// <remarks>
/// NOTE: This type is a workaround for https://github.com/dotnet/roslyn/issues/31007
/// and it can be deleted once that feature is implemented.
/// </remarks>
internal static class LValueFlowCapturesProvider
{
public static ImmutableDictionary<CaptureId, FlowCaptureKind> CreateLValueFlowCaptures(ControlFlowGraph cfg)
{
// This method identifies flow capture reference operations that are target of an assignment
// and marks them as lvalue flow captures.
// Control flow graph can also contain flow captures
// that are r-value captures at some point and l-values captures at other point in
// the flow graph. Specifically, for an ICoalesceOperation a flow capture acts
// as both an r-value and l-value flow capture.
ImmutableDictionary<CaptureId, FlowCaptureKind>.Builder lvalueFlowCaptureIdBuilder = null;
var rvalueFlowCaptureIds = PooledHashSet<CaptureId>.GetInstance();
try
{
foreach (var flowCaptureReference in cfg.DescendantOperations<IFlowCaptureReferenceOperation>(OperationKind.FlowCaptureReference))
{
if (flowCaptureReference.Parent is IAssignmentOperation assignment &&
assignment.Target == flowCaptureReference ||
flowCaptureReference.IsInLeftOfDeconstructionAssignment(out _))
{
lvalueFlowCaptureIdBuilder ??= ImmutableDictionary.CreateBuilder<CaptureId, FlowCaptureKind>();
var captureKind = flowCaptureReference.Parent.IsAnyCompoundAssignment() || rvalueFlowCaptureIds.Contains(flowCaptureReference.Id)
? FlowCaptureKind.LValueAndRValueCapture
: FlowCaptureKind.LValueCapture;
lvalueFlowCaptureIdBuilder.Add(flowCaptureReference.Id, captureKind);
}
else
{
rvalueFlowCaptureIds.Add(flowCaptureReference.Id);
}
}
#if DEBUG
if (lvalueFlowCaptureIdBuilder != null)
{
foreach (var (captureId, kind) in lvalueFlowCaptureIdBuilder)
Debug.Assert(kind == FlowCaptureKind.LValueAndRValueCapture || !rvalueFlowCaptureIds.Contains(captureId), "Flow capture used as both an r-value and an l-value, but with incorrect flow capture kind");
}
#endif
return lvalueFlowCaptureIdBuilder != null ? lvalueFlowCaptureIdBuilder.ToImmutable() : ImmutableDictionary<CaptureId, FlowCaptureKind>.Empty;
}
finally
{
rvalueFlowCaptureIds.Free();
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
#if DEBUG
using System.Diagnostics;
#endif
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Helper class to detect <see cref="IFlowCaptureOperation"/>s that are l-value captures.
/// L-value captures are essentially captures of a symbol's location/address.
/// Corresponding <see cref="IFlowCaptureReferenceOperation"/>s which share the same
/// <see cref="CaptureId"/> as this flow capture, dereferences and writes to this location
/// subsequently in the flow graph.
/// For example, consider the below code:
/// a[i] = x ?? a[j];
/// The control flow graph contains an initial flow capture of "a[i]" to capture the l-value
/// of this array element:
/// FC0 (a[i])
/// Then it evaluates the right hand side, which can have different
/// values on different control flow paths, and the resultant value is then written
/// to the captured location:
/// FCR0 = result
/// </summary>
/// <remarks>
/// NOTE: This type is a workaround for https://github.com/dotnet/roslyn/issues/31007
/// and it can be deleted once that feature is implemented.
/// </remarks>
internal static class LValueFlowCapturesProvider
{
public static ImmutableDictionary<CaptureId, FlowCaptureKind> CreateLValueFlowCaptures(ControlFlowGraph cfg)
{
// This method identifies flow capture reference operations that are target of an assignment
// and marks them as lvalue flow captures.
// Control flow graph can also contain flow captures
// that are r-value captures at some point and l-values captures at other point in
// the flow graph. Specifically, for an ICoalesceOperation a flow capture acts
// as both an r-value and l-value flow capture.
ImmutableDictionary<CaptureId, FlowCaptureKind>.Builder lvalueFlowCaptureIdBuilder = null;
var rvalueFlowCaptureIds = PooledHashSet<CaptureId>.GetInstance();
try
{
foreach (var flowCaptureReference in cfg.DescendantOperations<IFlowCaptureReferenceOperation>(OperationKind.FlowCaptureReference))
{
if (flowCaptureReference.Parent is IAssignmentOperation assignment &&
assignment.Target == flowCaptureReference ||
flowCaptureReference.IsInLeftOfDeconstructionAssignment(out _))
{
lvalueFlowCaptureIdBuilder ??= ImmutableDictionary.CreateBuilder<CaptureId, FlowCaptureKind>();
var captureKind = flowCaptureReference.Parent.IsAnyCompoundAssignment() || rvalueFlowCaptureIds.Contains(flowCaptureReference.Id)
? FlowCaptureKind.LValueAndRValueCapture
: FlowCaptureKind.LValueCapture;
lvalueFlowCaptureIdBuilder.Add(flowCaptureReference.Id, captureKind);
}
else
{
rvalueFlowCaptureIds.Add(flowCaptureReference.Id);
}
}
#if DEBUG
if (lvalueFlowCaptureIdBuilder != null)
{
foreach (var (captureId, kind) in lvalueFlowCaptureIdBuilder)
Debug.Assert(kind == FlowCaptureKind.LValueAndRValueCapture || !rvalueFlowCaptureIds.Contains(captureId), "Flow capture used as both an r-value and an l-value, but with incorrect flow capture kind");
}
#endif
return lvalueFlowCaptureIdBuilder != null ? lvalueFlowCaptureIdBuilder.ToImmutable() : ImmutableDictionary<CaptureId, FlowCaptureKind>.Empty;
}
finally
{
rvalueFlowCaptureIds.Free();
}
}
}
}
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/Workspaces/Core/Portable/Shared/TestHooks/AsynchronousOperationListener.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.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
internal sealed partial class AsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly NonReentrantLock _gate = new();
#pragma warning disable IDE0052 // Remove unread private members - Can this field be removed?
private readonly string _featureName;
#pragma warning restore IDE0052 // Remove unread private members
private readonly HashSet<TaskCompletionSource<bool>> _pendingTasks = new();
private CancellationTokenSource _expeditedDelayCancellationTokenSource;
private List<DiagnosticAsyncToken> _diagnosticTokenList = new();
private int _counter;
private bool _trackActiveTokens;
public AsynchronousOperationListener()
: this(featureName: "noname", enableDiagnosticTokens: false)
{
}
public AsynchronousOperationListener(string featureName, bool enableDiagnosticTokens)
{
_featureName = featureName;
_expeditedDelayCancellationTokenSource = new CancellationTokenSource();
TrackActiveTokens = Debugger.IsAttached || enableDiagnosticTokens;
}
public async Task<bool> Delay(TimeSpan delay, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var expeditedDelayCancellationToken = _expeditedDelayCancellationTokenSource.Token;
if (expeditedDelayCancellationToken.IsCancellationRequested)
{
// The operation is already being expedited
return false;
}
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, expeditedDelayCancellationToken);
try
{
await Task.Delay(delay, cancellationTokenSource.Token).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (expeditedDelayCancellationToken.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// The cancellation only occurred due to a request to expedite the operation
return false;
}
}
public IAsyncToken BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
using (_gate.DisposableWait(CancellationToken.None))
{
IAsyncToken asyncToken;
if (_trackActiveTokens)
{
var token = new DiagnosticAsyncToken(this, name, tag, filePath, lineNumber);
_diagnosticTokenList.Add(token);
asyncToken = token;
}
else
{
asyncToken = new AsyncToken(this);
}
return asyncToken;
}
}
private void Increment_NoLock()
{
Contract.ThrowIfFalse(_gate.LockHeldByMe());
_counter++;
}
private void Decrement_NoLock(AsyncToken token)
{
Contract.ThrowIfFalse(_gate.LockHeldByMe());
_counter--;
if (_counter == 0)
{
foreach (var task in _pendingTasks)
{
task.SetResult(true);
}
_pendingTasks.Clear();
// Replace the cancellation source used for expediting waits.
var oldSource = Interlocked.Exchange(ref _expeditedDelayCancellationTokenSource, new CancellationTokenSource());
oldSource.Dispose();
}
if (_trackActiveTokens)
{
var i = 0;
var removed = false;
while (i < _diagnosticTokenList.Count)
{
if (_diagnosticTokenList[i] == token)
{
_diagnosticTokenList.RemoveAt(i);
removed = true;
break;
}
i++;
}
Debug.Assert(removed, "IAsyncToken and Listener mismatch");
}
}
public Task ExpeditedWaitAsync()
{
using (_gate.DisposableWait(CancellationToken.None))
{
if (_counter == 0)
{
// There is nothing to wait for, so we are immediately done
return Task.CompletedTask;
}
else
{
// Use CancelAfter to ensure cancellation callbacks are not synchronously invoked under the _gate.
_expeditedDelayCancellationTokenSource.CancelAfter(TimeSpan.Zero);
// Calling SetResult on a normal TaskCompletionSource can cause continuations to run synchronously
// at that point. That's a problem as that may cause additional code to run while we're holding a lock.
// In order to prevent that, we pass along RunContinuationsAsynchronously in order to ensure that
// all continuations will run at a future point when this thread has released the lock.
var source = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_pendingTasks.Add(source);
return source.Task;
}
}
}
public async Task WaitUntilConditionIsMetAsync(Func<IEnumerable<DiagnosticAsyncToken>, bool> condition)
{
Contract.ThrowIfFalse(TrackActiveTokens);
while (true)
{
if (condition(ActiveDiagnosticTokens))
{
break;
}
await Task.Delay(TimeSpan.FromMilliseconds(10)).ConfigureAwait(false);
}
}
public bool TrackActiveTokens
{
get { return _trackActiveTokens; }
set
{
using (_gate.DisposableWait(CancellationToken.None))
{
if (_trackActiveTokens == value)
{
return;
}
_trackActiveTokens = value;
_diagnosticTokenList = new List<DiagnosticAsyncToken>();
}
}
}
public bool HasPendingWork
{
get
{
using (_gate.DisposableWait(CancellationToken.None))
{
return _counter != 0;
}
}
}
public ImmutableArray<DiagnosticAsyncToken> ActiveDiagnosticTokens
{
get
{
using (_gate.DisposableWait(CancellationToken.None))
{
if (_diagnosticTokenList == null)
{
return ImmutableArray<DiagnosticAsyncToken>.Empty;
}
return _diagnosticTokenList.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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.TestHooks
{
internal sealed partial class AsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter
{
private readonly NonReentrantLock _gate = new();
#pragma warning disable IDE0052 // Remove unread private members - Can this field be removed?
private readonly string _featureName;
#pragma warning restore IDE0052 // Remove unread private members
private readonly HashSet<TaskCompletionSource<bool>> _pendingTasks = new();
private CancellationTokenSource _expeditedDelayCancellationTokenSource;
private List<DiagnosticAsyncToken> _diagnosticTokenList = new();
private int _counter;
private bool _trackActiveTokens;
public AsynchronousOperationListener()
: this(featureName: "noname", enableDiagnosticTokens: false)
{
}
public AsynchronousOperationListener(string featureName, bool enableDiagnosticTokens)
{
_featureName = featureName;
_expeditedDelayCancellationTokenSource = new CancellationTokenSource();
TrackActiveTokens = Debugger.IsAttached || enableDiagnosticTokens;
}
public async Task<bool> Delay(TimeSpan delay, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
var expeditedDelayCancellationToken = _expeditedDelayCancellationTokenSource.Token;
if (expeditedDelayCancellationToken.IsCancellationRequested)
{
// The operation is already being expedited
return false;
}
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, expeditedDelayCancellationToken);
try
{
await Task.Delay(delay, cancellationTokenSource.Token).ConfigureAwait(false);
return true;
}
catch (OperationCanceledException) when (expeditedDelayCancellationToken.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
{
// The cancellation only occurred due to a request to expedite the operation
return false;
}
}
public IAsyncToken BeginAsyncOperation(string name, object? tag = null, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNumber = 0)
{
using (_gate.DisposableWait(CancellationToken.None))
{
IAsyncToken asyncToken;
if (_trackActiveTokens)
{
var token = new DiagnosticAsyncToken(this, name, tag, filePath, lineNumber);
_diagnosticTokenList.Add(token);
asyncToken = token;
}
else
{
asyncToken = new AsyncToken(this);
}
return asyncToken;
}
}
private void Increment_NoLock()
{
Contract.ThrowIfFalse(_gate.LockHeldByMe());
_counter++;
}
private void Decrement_NoLock(AsyncToken token)
{
Contract.ThrowIfFalse(_gate.LockHeldByMe());
_counter--;
if (_counter == 0)
{
foreach (var task in _pendingTasks)
{
task.SetResult(true);
}
_pendingTasks.Clear();
// Replace the cancellation source used for expediting waits.
var oldSource = Interlocked.Exchange(ref _expeditedDelayCancellationTokenSource, new CancellationTokenSource());
oldSource.Dispose();
}
if (_trackActiveTokens)
{
var i = 0;
var removed = false;
while (i < _diagnosticTokenList.Count)
{
if (_diagnosticTokenList[i] == token)
{
_diagnosticTokenList.RemoveAt(i);
removed = true;
break;
}
i++;
}
Debug.Assert(removed, "IAsyncToken and Listener mismatch");
}
}
public Task ExpeditedWaitAsync()
{
using (_gate.DisposableWait(CancellationToken.None))
{
if (_counter == 0)
{
// There is nothing to wait for, so we are immediately done
return Task.CompletedTask;
}
else
{
// Use CancelAfter to ensure cancellation callbacks are not synchronously invoked under the _gate.
_expeditedDelayCancellationTokenSource.CancelAfter(TimeSpan.Zero);
// Calling SetResult on a normal TaskCompletionSource can cause continuations to run synchronously
// at that point. That's a problem as that may cause additional code to run while we're holding a lock.
// In order to prevent that, we pass along RunContinuationsAsynchronously in order to ensure that
// all continuations will run at a future point when this thread has released the lock.
var source = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_pendingTasks.Add(source);
return source.Task;
}
}
}
public async Task WaitUntilConditionIsMetAsync(Func<IEnumerable<DiagnosticAsyncToken>, bool> condition)
{
Contract.ThrowIfFalse(TrackActiveTokens);
while (true)
{
if (condition(ActiveDiagnosticTokens))
{
break;
}
await Task.Delay(TimeSpan.FromMilliseconds(10)).ConfigureAwait(false);
}
}
public bool TrackActiveTokens
{
get { return _trackActiveTokens; }
set
{
using (_gate.DisposableWait(CancellationToken.None))
{
if (_trackActiveTokens == value)
{
return;
}
_trackActiveTokens = value;
_diagnosticTokenList = new List<DiagnosticAsyncToken>();
}
}
}
public bool HasPendingWork
{
get
{
using (_gate.DisposableWait(CancellationToken.None))
{
return _counter != 0;
}
}
}
public ImmutableArray<DiagnosticAsyncToken> ActiveDiagnosticTokens
{
get
{
using (_gate.DisposableWait(CancellationToken.None))
{
if (_diagnosticTokenList == null)
{
return ImmutableArray<DiagnosticAsyncToken>.Empty;
}
return _diagnosticTokenList.ToImmutableArray();
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/My Project/launchSettings.json | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | {
"profiles": {
"xUnit.net Console (32-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.x86.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
},
"xUnit.net Console (64-bit)": {
"commandName": "Executable",
"executablePath": "$(NuGetPackageRoot)xunit.runner.console\\$(XUnitVersion)\\tools\\net452\\xunit.console.exe",
"commandLineArgs": "$(TargetPath) -noshadow -verbose"
}
}
} | -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/Compilers/CSharp/Portable/Symbols/PublicModel/DiscardSymbol.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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class DiscardSymbol : Symbol, IDiscardSymbol
{
private readonly Symbols.DiscardSymbol _underlying;
private ITypeSymbol? _lazyType;
public DiscardSymbol(Symbols.DiscardSymbol underlying)
{
RoslynDebug.Assert(underlying != null);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
ITypeSymbol IDiscardSymbol.Type
{
get
{
if (_lazyType is null)
{
Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyType;
}
}
CodeAnalysis.NullableAnnotation IDiscardSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation();
protected override void Accept(SymbolVisitor visitor) => visitor.VisitDiscard(this);
protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscard(this);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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 Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols.PublicModel
{
internal sealed class DiscardSymbol : Symbol, IDiscardSymbol
{
private readonly Symbols.DiscardSymbol _underlying;
private ITypeSymbol? _lazyType;
public DiscardSymbol(Symbols.DiscardSymbol underlying)
{
RoslynDebug.Assert(underlying != null);
_underlying = underlying;
}
internal override CSharp.Symbol UnderlyingSymbol => _underlying;
ITypeSymbol IDiscardSymbol.Type
{
get
{
if (_lazyType is null)
{
Interlocked.CompareExchange(ref _lazyType, _underlying.TypeWithAnnotations.GetPublicSymbol(), null);
}
return _lazyType;
}
}
CodeAnalysis.NullableAnnotation IDiscardSymbol.NullableAnnotation => _underlying.TypeWithAnnotations.ToPublicAnnotation();
protected override void Accept(SymbolVisitor visitor) => visitor.VisitDiscard(this);
protected override TResult? Accept<TResult>(SymbolVisitor<TResult> visitor) where TResult : default => visitor.VisitDiscard(this);
}
}
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/EditorFeatures/Test2/Simplification/BlockSimplificationTests.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.CodeStyle
Imports Microsoft.CodeAnalysis.CSharp.CodeStyle
Imports Microsoft.CodeAnalysis.Options
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class SimplificationTests
Inherits AbstractSimplificationTests
Private Shared ReadOnly DoNotPreferBraces As Dictionary(Of OptionKey2, Object) = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CSharpCodeStyleOptions.PreferBraces), New CodeStyleOption2(Of PreferBracesPreference)(PreferBracesPreference.None, NotificationOption2.Silent)}}
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DoNotSimplifyIfBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
if (true)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
if (true)
{
return;
}
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DoNotSimplifyMethodBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{|Simplify:{
return;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DoNotSimplifyTryBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
try
{|Simplify:{
return;
}|}
finally
{
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
try
{
return;
}
finally
{
}
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyIfBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
if (true)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
if (true)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyElseBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
if (true)
{
}
else
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
if (true)
{
}
else
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyWhileBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
while (true)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
while (true)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyDoBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
do
{|Simplify:{
return;
}|}
while (true);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
do
return;
while (true);
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyUsingBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
using (x)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
using (x)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyLockBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
lock (x)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
lock (x)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyForBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
for (;;)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
for (;;)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyForeachBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
foreach (var x in y)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
foreach (var x in y)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
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.CodeStyle
Imports Microsoft.CodeAnalysis.CSharp.CodeStyle
Imports Microsoft.CodeAnalysis.Options
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Simplification
Public Class SimplificationTests
Inherits AbstractSimplificationTests
Private Shared ReadOnly DoNotPreferBraces As Dictionary(Of OptionKey2, Object) = New Dictionary(Of OptionKey2, Object) From {{New OptionKey2(CSharpCodeStyleOptions.PreferBraces), New CodeStyleOption2(Of PreferBracesPreference)(PreferBracesPreference.None, NotificationOption2.Silent)}}
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DoNotSimplifyIfBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
if (true)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
if (true)
{
return;
}
}
}
</code>
Await TestAsync(input, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DoNotSimplifyMethodBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{|Simplify:{
return;
}|}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_DoNotSimplifyTryBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
try
{|Simplify:{
return;
}|}
finally
{
}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
try
{
return;
}
finally
{
}
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyIfBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
if (true)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
if (true)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyElseBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
if (true)
{
}
else
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
if (true)
{
}
else
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyWhileBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
while (true)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
while (true)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyDoBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
do
{|Simplify:{
return;
}|}
while (true);
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
do
return;
while (true);
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyUsingBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
using (x)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
using (x)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyLockBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
lock (x)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
lock (x)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyForBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
for (;;)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
for (;;)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Simplification)>
Public Async Function TestCSharp_SimplifyForeachBlock() As Task
Dim input =
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
foreach (var x in y)
{|Simplify:{
return;
}|}
}
}
</Document>
</Project>
</Workspace>
Dim expected =
<code>
class Program
{
void M()
{
foreach (var x in y)
return;
}
}
</code>
Await TestAsync(input, expected, DoNotPreferBraces)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/VisualStudio/Core/Def/Implementation/CallHierarchy/Finders/FieldReferenceFinder.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
{
internal class FieldReferenceFinder : AbstractCallFinder
{
public FieldReferenceFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider)
: base(symbol, projectId, asyncListener, provider)
{
}
public override string DisplayName
{
get
{
return string.Format(EditorFeaturesResources.References_To_Field_0, SymbolName);
}
}
protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken)
{
var callers = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false);
return callers.Where(c => c.IsDirect);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Shared.TestHooks;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CallHierarchy.Finders
{
internal class FieldReferenceFinder : AbstractCallFinder
{
public FieldReferenceFinder(ISymbol symbol, ProjectId projectId, IAsynchronousOperationListener asyncListener, CallHierarchyProvider provider)
: base(symbol, projectId, asyncListener, provider)
{
}
public override string DisplayName
{
get
{
return string.Format(EditorFeaturesResources.References_To_Field_0, SymbolName);
}
}
protected override async Task<IEnumerable<SymbolCallerInfo>> GetCallersAsync(ISymbol symbol, Project project, IImmutableSet<Document> documents, CancellationToken cancellationToken)
{
var callers = await SymbolFinder.FindCallersAsync(symbol, project.Solution, documents, cancellationToken).ConfigureAwait(false);
return callers.Where(c => c.IsDirect);
}
}
}
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmDataItem.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
namespace Microsoft.VisualStudio.Debugger
{
public class DkmDataItem
{
protected virtual void OnClose() { }
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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
namespace Microsoft.VisualStudio.Debugger
{
public class DkmDataItem
{
protected virtual void OnClose() { }
}
}
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/SyntaxTokenExtensions.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;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
internal static partial class SyntaxTokenExtensions
{
public static bool IsUsingOrExternKeyword(this SyntaxToken token)
{
return
token.Kind() == SyntaxKind.UsingKeyword ||
token.Kind() == SyntaxKind.ExternKeyword;
}
public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.UsingKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.UsingKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.StaticKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.StaticKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsBeginningOfStatementContext(this SyntaxToken token)
{
// cases:
// {
// |
// }
// |
// Note, the following is *not* a legal statement context:
// do { } |
// ...;
// |
// case 0:
// |
// default:
// |
// label:
// |
// if (goo)
// |
// while (true)
// |
// do
// |
// for (;;)
// |
// foreach (var v in c)
// |
// else
// |
// using (expr)
// |
// fixed (void* v = &expr)
// |
// lock (expr)
// |
// for ( ; ; Goo(), |
// After attribute lists on a statement:
// [Bar]
// |
switch (token.Kind())
{
case SyntaxKind.OpenBraceToken when token.Parent.IsKind(SyntaxKind.Block):
return true;
case SyntaxKind.SemicolonToken:
var statement = token.GetAncestor<StatementSyntax>();
return statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
statement.GetLastToken(includeZeroWidth: true) == token;
case SyntaxKind.CloseBraceToken:
if (token.Parent.IsKind(SyntaxKind.Block))
{
if (token.Parent.Parent is StatementSyntax)
{
// Most blocks that are the child of statement are places
// that we can follow with another statement. i.e.:
// if { }
// while () { }
// There are two exceptions.
// try {}
// do {}
if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
!token.Parent.IsParentKind(SyntaxKind.DoStatement))
{
return true;
}
}
else if (
token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
token.Parent.IsParentKind(SyntaxKind.SwitchSection))
{
return true;
}
}
if (token.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
return false;
case SyntaxKind.ColonToken:
return token.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.CasePatternSwitchLabel,
SyntaxKind.LabeledStatement);
case SyntaxKind.DoKeyword when token.Parent.IsKind(SyntaxKind.DoStatement):
return true;
case SyntaxKind.CloseParenToken:
var parent = token.Parent;
return parent.IsKind(SyntaxKind.ForStatement) ||
parent.IsKind(SyntaxKind.ForEachStatement) ||
parent.IsKind(SyntaxKind.ForEachVariableStatement) ||
parent.IsKind(SyntaxKind.WhileStatement) ||
parent.IsKind(SyntaxKind.IfStatement) ||
parent.IsKind(SyntaxKind.LockStatement) ||
parent.IsKind(SyntaxKind.UsingStatement) ||
parent.IsKind(SyntaxKind.FixedStatement);
case SyntaxKind.ElseKeyword:
return token.Parent.IsKind(SyntaxKind.ElseClause);
case SyntaxKind.CloseBracketToken:
if (token.Parent.IsKind(SyntaxKind.AttributeList))
{
// attributes can belong to a statement
var container = token.Parent.Parent;
if (container is StatementSyntax)
{
return true;
}
}
return false;
}
return false;
}
public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
{
// cases:
// }
// |
// ...;
// |
// extern alias Goo;
// using System;
// |
// [assembly: Goo]
// |
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
if (token.Kind() == SyntaxKind.CloseBracketToken)
{
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
return false;
}
public static bool IsAfterPossibleCast(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CloseParenToken)
{
if (token.Parent.IsKind(SyntaxKind.CastExpression))
{
return true;
}
if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr))
{
var expr = parenExpr.Expression;
if (expr is TypeSyntax)
{
return true;
}
}
}
return false;
}
public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
{
if (token.IsLastTokenOfNode<QueryClauseSyntax>())
{
return true;
}
if (token.Kind() == SyntaxKind.IdentifierToken &&
token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
{
return true;
}
return false;
}
public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
{
// cases:
// #if |
// #if goo || |
// #if goo && |
// #if ( |
// #if ! |
// Same for elif
if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
{
return false;
}
// #if
// #elif
if (targetToken.Kind() == SyntaxKind.IfKeyword ||
targetToken.Kind() == SyntaxKind.ElifKeyword)
{
return true;
}
// ( |
if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// ! |
if (targetToken.Parent is PrefixUnaryExpressionSyntax prefix)
{
return prefix.OperatorToken == targetToken;
}
// a &&
// a ||
if (targetToken.Parent is BinaryExpressionSyntax binary)
{
return binary.OperatorToken == targetToken;
}
return false;
}
public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
{
// cases:
// orderby a |
// orderby a a|
// orderby a, b |
// orderby a, b a|
if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
{
return false;
}
var ordering = targetToken.GetAncestor<OrderingSyntax>();
if (ordering == null)
{
return false;
}
// orderby a |
// orderby a, b |
var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
if (targetToken == lastToken)
{
return true;
}
return false;
}
public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
{
// cases:
// case X: |
// default: |
// switch (e) { |
//
// case X: Statement(); |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.ColonToken)
{
if (targetToken.Parent.IsKind(
SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
targetToken.Kind() == SyntaxKind.CloseBraceToken)
{
var section = targetToken.GetAncestor<SwitchSectionSyntax>();
if (section != null)
{
foreach (var statement in section.Statements)
{
if (targetToken == statement.GetLastToken(includeSkipped: true))
{
return true;
}
}
}
}
return false;
}
public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
{
return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
&& targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
}
public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
{
// cases:
// Goo( |
// Goo(expr, |
// Goo(bar: |
// new Goo( |
// new Goo(expr, |
// new Goo(bar: |
// Goo : base( |
// Goo : base(bar: |
// Goo : this( |
// Goo : this(bar: |
// Goo(bar: |
if (targetToken.Kind() == SyntaxKind.ColonToken &&
targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.Argument) &&
targetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList))
{
var owner = targetToken.Parent.Parent.Parent.Parent;
if (owner.IsKind(SyntaxKind.InvocationExpression) ||
owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
owner.IsKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
targetToken.Kind() == SyntaxKind.CommaToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
{
if (targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
// var( |
// var(expr, |
// Those are more likely to be deconstruction-declarations being typed than invocations a method "var"
if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) && !targetToken.IsInvocationOfVarExpression())
{
return true;
}
}
}
return false;
}
public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
{
if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
{
return true;
}
return false;
}
public static bool IsUnsafeContext(this SyntaxToken targetToken)
{
return
targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
{
// yield |
// yield r|
return targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword);
}
public static bool IsAnyAccessorDeclarationContext(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
{
return targetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, kind);
}
public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
where TMemberNode : SyntaxNode
{
if (!IsAccessorDeclarationContextWorker(ref targetToken))
{
return false;
}
var list = targetToken.GetAncestor<AccessorListSyntax>();
if (list == null)
{
return false;
}
// Check if we already have this accessor. (however, don't count it
// if the user is *on* that accessor.
var existingAccessor = list.Accessors
.Select(a => a.Keyword)
.FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
if (existingAccessor.Kind() != SyntaxKind.None)
{
var existingAccessorSpan = existingAccessor.Span;
if (!existingAccessorSpan.IntersectsWith(position))
{
return false;
}
}
var decl = targetToken.GetAncestor<TMemberNode>();
return decl != null;
}
private static bool IsAccessorDeclarationContextWorker(ref SyntaxToken targetToken)
{
// cases:
// int Goo { |
// int Goo { private |
// int Goo { set { } |
// int Goo { set; |
// int Goo { [Bar]|
// int Goo { readonly |
// Consume all preceding access modifiers
while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
targetToken.Kind() == SyntaxKind.PublicKeyword ||
targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
targetToken.Kind() == SyntaxKind.PrivateKeyword ||
targetToken.Kind() == SyntaxKind.ReadOnlyKeyword)
{
targetToken = targetToken.GetPreviousToken(includeSkipped: true);
}
// int Goo { |
// int Goo { private |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.AccessorList))
{
return true;
}
// int Goo { set { } |
// int Goo { set { } private |
if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.Block) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { set; |
if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
targetToken.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { [Bar]|
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
return false;
}
private static bool IsGenericInterfaceOrDelegateTypeParameterList([NotNullWhen(true)] SyntaxNode? node)
{
if (node.IsKind(SyntaxKind.TypeParameterList))
{
if (node.IsParentKind(SyntaxKind.InterfaceDeclaration, out TypeDeclarationSyntax? typeDecl))
return typeDecl.TypeParameterList == node;
else if (node.IsParentKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl))
return delegateDecl.TypeParameterList == node;
}
return false;
}
public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
{
// cases:
// interface IGoo<|
// interface IGoo<A,|
// interface IGoo<[Bar]|
// delegate X D<|
// delegate X D<A,|
// delegate X D<[Bar]|
if (targetToken.Kind() == SyntaxKind.LessThanToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CommaToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.TypeParameter) &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.Parent.Parent))
{
return true;
}
return false;
}
public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
{
var argumentList = (BaseArgumentListSyntax)token.Parent;
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
if (item.AsNode() is ArgumentSyntax node && node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
public static bool IsNumericTypeContext(this SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!(token.Parent is MemberAccessExpressionSyntax memberAccessExpression))
{
return false;
}
var typeInfo = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken);
return typeInfo.Type.IsNumericType();
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery
{
internal static partial class SyntaxTokenExtensions
{
public static bool IsUsingOrExternKeyword(this SyntaxToken token)
{
return
token.Kind() == SyntaxKind.UsingKeyword ||
token.Kind() == SyntaxKind.ExternKeyword;
}
public static bool IsUsingKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.UsingKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.UsingKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsStaticKeywordInUsingDirective(this SyntaxToken token)
{
if (token.IsKind(SyntaxKind.StaticKeyword))
{
var usingDirective = token.GetAncestor<UsingDirectiveSyntax>();
if (usingDirective != null &&
usingDirective.StaticKeyword == token)
{
return true;
}
}
return false;
}
public static bool IsBeginningOfStatementContext(this SyntaxToken token)
{
// cases:
// {
// |
// }
// |
// Note, the following is *not* a legal statement context:
// do { } |
// ...;
// |
// case 0:
// |
// default:
// |
// label:
// |
// if (goo)
// |
// while (true)
// |
// do
// |
// for (;;)
// |
// foreach (var v in c)
// |
// else
// |
// using (expr)
// |
// fixed (void* v = &expr)
// |
// lock (expr)
// |
// for ( ; ; Goo(), |
// After attribute lists on a statement:
// [Bar]
// |
switch (token.Kind())
{
case SyntaxKind.OpenBraceToken when token.Parent.IsKind(SyntaxKind.Block):
return true;
case SyntaxKind.SemicolonToken:
var statement = token.GetAncestor<StatementSyntax>();
return statement != null && !statement.IsParentKind(SyntaxKind.GlobalStatement) &&
statement.GetLastToken(includeZeroWidth: true) == token;
case SyntaxKind.CloseBraceToken:
if (token.Parent.IsKind(SyntaxKind.Block))
{
if (token.Parent.Parent is StatementSyntax)
{
// Most blocks that are the child of statement are places
// that we can follow with another statement. i.e.:
// if { }
// while () { }
// There are two exceptions.
// try {}
// do {}
if (!token.Parent.IsParentKind(SyntaxKind.TryStatement) &&
!token.Parent.IsParentKind(SyntaxKind.DoStatement))
{
return true;
}
}
else if (
token.Parent.IsParentKind(SyntaxKind.ElseClause) ||
token.Parent.IsParentKind(SyntaxKind.FinallyClause) ||
token.Parent.IsParentKind(SyntaxKind.CatchClause) ||
token.Parent.IsParentKind(SyntaxKind.SwitchSection))
{
return true;
}
}
if (token.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
return false;
case SyntaxKind.ColonToken:
return token.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.CasePatternSwitchLabel,
SyntaxKind.LabeledStatement);
case SyntaxKind.DoKeyword when token.Parent.IsKind(SyntaxKind.DoStatement):
return true;
case SyntaxKind.CloseParenToken:
var parent = token.Parent;
return parent.IsKind(SyntaxKind.ForStatement) ||
parent.IsKind(SyntaxKind.ForEachStatement) ||
parent.IsKind(SyntaxKind.ForEachVariableStatement) ||
parent.IsKind(SyntaxKind.WhileStatement) ||
parent.IsKind(SyntaxKind.IfStatement) ||
parent.IsKind(SyntaxKind.LockStatement) ||
parent.IsKind(SyntaxKind.UsingStatement) ||
parent.IsKind(SyntaxKind.FixedStatement);
case SyntaxKind.ElseKeyword:
return token.Parent.IsKind(SyntaxKind.ElseClause);
case SyntaxKind.CloseBracketToken:
if (token.Parent.IsKind(SyntaxKind.AttributeList))
{
// attributes can belong to a statement
var container = token.Parent.Parent;
if (container is StatementSyntax)
{
return true;
}
}
return false;
}
return false;
}
public static bool IsBeginningOfGlobalStatementContext(this SyntaxToken token)
{
// cases:
// }
// |
// ...;
// |
// extern alias Goo;
// using System;
// |
// [assembly: Goo]
// |
if (token.Kind() == SyntaxKind.CloseBraceToken)
{
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
}
if (token.Kind() == SyntaxKind.SemicolonToken)
{
var globalStatement = token.GetAncestor<GlobalStatementSyntax>();
if (globalStatement != null && globalStatement.GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
if (memberDeclaration != null && memberDeclaration.GetLastToken(includeZeroWidth: true) == token &&
memberDeclaration.IsParentKind(SyntaxKind.CompilationUnit))
{
return true;
}
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
if (compUnit.Externs.Count > 0 && compUnit.Externs.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
if (token.Kind() == SyntaxKind.CloseBracketToken)
{
var compUnit = token.GetAncestor<CompilationUnitSyntax>();
if (compUnit != null)
{
if (compUnit.AttributeLists.Count > 0 && compUnit.AttributeLists.Last().GetLastToken(includeZeroWidth: true) == token)
{
return true;
}
}
}
return false;
}
public static bool IsAfterPossibleCast(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CloseParenToken)
{
if (token.Parent.IsKind(SyntaxKind.CastExpression))
{
return true;
}
if (token.Parent.IsKind(SyntaxKind.ParenthesizedExpression, out ParenthesizedExpressionSyntax? parenExpr))
{
var expr = parenExpr.Expression;
if (expr is TypeSyntax)
{
return true;
}
}
}
return false;
}
public static bool IsLastTokenOfQueryClause(this SyntaxToken token)
{
if (token.IsLastTokenOfNode<QueryClauseSyntax>())
{
return true;
}
if (token.Kind() == SyntaxKind.IdentifierToken &&
token.GetPreviousToken(includeSkipped: true).Kind() == SyntaxKind.IntoKeyword)
{
return true;
}
return false;
}
public static bool IsPreProcessorExpressionContext(this SyntaxToken targetToken)
{
// cases:
// #if |
// #if goo || |
// #if goo && |
// #if ( |
// #if ! |
// Same for elif
if (targetToken.GetAncestor<ConditionalDirectiveTriviaSyntax>() == null)
{
return false;
}
// #if
// #elif
if (targetToken.Kind() == SyntaxKind.IfKeyword ||
targetToken.Kind() == SyntaxKind.ElifKeyword)
{
return true;
}
// ( |
if (targetToken.Kind() == SyntaxKind.OpenParenToken &&
targetToken.Parent.IsKind(SyntaxKind.ParenthesizedExpression))
{
return true;
}
// ! |
if (targetToken.Parent is PrefixUnaryExpressionSyntax prefix)
{
return prefix.OperatorToken == targetToken;
}
// a &&
// a ||
if (targetToken.Parent is BinaryExpressionSyntax binary)
{
return binary.OperatorToken == targetToken;
}
return false;
}
public static bool IsOrderByDirectionContext(this SyntaxToken targetToken)
{
// cases:
// orderby a |
// orderby a a|
// orderby a, b |
// orderby a, b a|
if (!targetToken.IsKind(SyntaxKind.IdentifierToken, SyntaxKind.CloseParenToken, SyntaxKind.CloseBracketToken))
{
return false;
}
var ordering = targetToken.GetAncestor<OrderingSyntax>();
if (ordering == null)
{
return false;
}
// orderby a |
// orderby a, b |
var lastToken = ordering.Expression.GetLastToken(includeSkipped: true);
if (targetToken == lastToken)
{
return true;
}
return false;
}
public static bool IsSwitchLabelContext(this SyntaxToken targetToken)
{
// cases:
// case X: |
// default: |
// switch (e) { |
//
// case X: Statement(); |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.SwitchStatement))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.ColonToken)
{
if (targetToken.Parent.IsKind(
SyntaxKind.CaseSwitchLabel, SyntaxKind.DefaultSwitchLabel, SyntaxKind.CasePatternSwitchLabel))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.SemicolonToken ||
targetToken.Kind() == SyntaxKind.CloseBraceToken)
{
var section = targetToken.GetAncestor<SwitchSectionSyntax>();
if (section != null)
{
foreach (var statement in section.Statements)
{
if (targetToken == statement.GetLastToken(includeSkipped: true))
{
return true;
}
}
}
}
return false;
}
public static bool IsXmlCrefParameterModifierContext(this SyntaxToken targetToken)
{
return targetToken.IsKind(SyntaxKind.CommaToken, SyntaxKind.OpenParenToken)
&& targetToken.Parent.IsKind(SyntaxKind.CrefBracketedParameterList, SyntaxKind.CrefParameterList);
}
public static bool IsConstructorOrMethodParameterArgumentContext(this SyntaxToken targetToken)
{
// cases:
// Goo( |
// Goo(expr, |
// Goo(bar: |
// new Goo( |
// new Goo(expr, |
// new Goo(bar: |
// Goo : base( |
// Goo : base(bar: |
// Goo : this( |
// Goo : this(bar: |
// Goo(bar: |
if (targetToken.Kind() == SyntaxKind.ColonToken &&
targetToken.Parent.IsKind(SyntaxKind.NameColon) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.Argument) &&
targetToken.Parent.Parent.Parent.IsKind(SyntaxKind.ArgumentList))
{
var owner = targetToken.Parent.Parent.Parent.Parent;
if (owner.IsKind(SyntaxKind.InvocationExpression) ||
owner.IsKind(SyntaxKind.ObjectCreationExpression) ||
owner.IsKind(SyntaxKind.BaseConstructorInitializer) ||
owner.IsKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
}
if (targetToken.Kind() == SyntaxKind.OpenParenToken ||
targetToken.Kind() == SyntaxKind.CommaToken)
{
if (targetToken.Parent.IsKind(SyntaxKind.ArgumentList))
{
if (targetToken.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression) ||
targetToken.Parent.IsParentKind(SyntaxKind.BaseConstructorInitializer) ||
targetToken.Parent.IsParentKind(SyntaxKind.ThisConstructorInitializer))
{
return true;
}
// var( |
// var(expr, |
// Those are more likely to be deconstruction-declarations being typed than invocations a method "var"
if (targetToken.Parent.IsParentKind(SyntaxKind.InvocationExpression) && !targetToken.IsInvocationOfVarExpression())
{
return true;
}
}
}
return false;
}
public static bool IsUnaryOperatorContext(this SyntaxToken targetToken)
{
if (targetToken.Kind() == SyntaxKind.OperatorKeyword &&
targetToken.GetPreviousToken(includeSkipped: true).IsLastTokenOfNode<TypeSyntax>())
{
return true;
}
return false;
}
public static bool IsUnsafeContext(this SyntaxToken targetToken)
{
return
targetToken.GetAncestors<StatementSyntax>().Any(s => s.IsKind(SyntaxKind.UnsafeStatement)) ||
targetToken.GetAncestors<MemberDeclarationSyntax>().Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsAfterYieldKeyword(this SyntaxToken targetToken)
{
// yield |
// yield r|
return targetToken.IsKindOrHasMatchingText(SyntaxKind.YieldKeyword);
}
public static bool IsAnyAccessorDeclarationContext(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
{
return targetToken.IsAccessorDeclarationContext<EventDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<PropertyDeclarationSyntax>(position, kind) ||
targetToken.IsAccessorDeclarationContext<IndexerDeclarationSyntax>(position, kind);
}
public static bool IsAccessorDeclarationContext<TMemberNode>(this SyntaxToken targetToken, int position, SyntaxKind kind = SyntaxKind.None)
where TMemberNode : SyntaxNode
{
if (!IsAccessorDeclarationContextWorker(ref targetToken))
{
return false;
}
var list = targetToken.GetAncestor<AccessorListSyntax>();
if (list == null)
{
return false;
}
// Check if we already have this accessor. (however, don't count it
// if the user is *on* that accessor.
var existingAccessor = list.Accessors
.Select(a => a.Keyword)
.FirstOrDefault(a => !a.IsMissing && a.IsKindOrHasMatchingText(kind));
if (existingAccessor.Kind() != SyntaxKind.None)
{
var existingAccessorSpan = existingAccessor.Span;
if (!existingAccessorSpan.IntersectsWith(position))
{
return false;
}
}
var decl = targetToken.GetAncestor<TMemberNode>();
return decl != null;
}
private static bool IsAccessorDeclarationContextWorker(ref SyntaxToken targetToken)
{
// cases:
// int Goo { |
// int Goo { private |
// int Goo { set { } |
// int Goo { set; |
// int Goo { [Bar]|
// int Goo { readonly |
// Consume all preceding access modifiers
while (targetToken.Kind() == SyntaxKind.InternalKeyword ||
targetToken.Kind() == SyntaxKind.PublicKeyword ||
targetToken.Kind() == SyntaxKind.ProtectedKeyword ||
targetToken.Kind() == SyntaxKind.PrivateKeyword ||
targetToken.Kind() == SyntaxKind.ReadOnlyKeyword)
{
targetToken = targetToken.GetPreviousToken(includeSkipped: true);
}
// int Goo { |
// int Goo { private |
if (targetToken.Kind() == SyntaxKind.OpenBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.AccessorList))
{
return true;
}
// int Goo { set { } |
// int Goo { set { } private |
if (targetToken.Kind() == SyntaxKind.CloseBraceToken &&
targetToken.Parent.IsKind(SyntaxKind.Block) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { set; |
if (targetToken.Kind() == SyntaxKind.SemicolonToken &&
targetToken.Parent is AccessorDeclarationSyntax)
{
return true;
}
// int Goo { [Bar]|
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent is AccessorDeclarationSyntax)
{
return true;
}
return false;
}
private static bool IsGenericInterfaceOrDelegateTypeParameterList([NotNullWhen(true)] SyntaxNode? node)
{
if (node.IsKind(SyntaxKind.TypeParameterList))
{
if (node.IsParentKind(SyntaxKind.InterfaceDeclaration, out TypeDeclarationSyntax? typeDecl))
return typeDecl.TypeParameterList == node;
else if (node.IsParentKind(SyntaxKind.DelegateDeclaration, out DelegateDeclarationSyntax? delegateDecl))
return delegateDecl.TypeParameterList == node;
}
return false;
}
public static bool IsTypeParameterVarianceContext(this SyntaxToken targetToken)
{
// cases:
// interface IGoo<|
// interface IGoo<A,|
// interface IGoo<[Bar]|
// delegate X D<|
// delegate X D<A,|
// delegate X D<[Bar]|
if (targetToken.Kind() == SyntaxKind.LessThanToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CommaToken &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent!))
{
return true;
}
if (targetToken.Kind() == SyntaxKind.CloseBracketToken &&
targetToken.Parent.IsKind(SyntaxKind.AttributeList) &&
targetToken.Parent.Parent.IsKind(SyntaxKind.TypeParameter) &&
IsGenericInterfaceOrDelegateTypeParameterList(targetToken.Parent.Parent.Parent))
{
return true;
}
return false;
}
public static bool IsMandatoryNamedParameterPosition(this SyntaxToken token)
{
if (token.Kind() == SyntaxKind.CommaToken && token.Parent is BaseArgumentListSyntax)
{
var argumentList = (BaseArgumentListSyntax)token.Parent;
foreach (var item in argumentList.Arguments.GetWithSeparators())
{
if (item.IsToken && item.AsToken() == token)
{
return false;
}
if (item.IsNode)
{
if (item.AsNode() is ArgumentSyntax node && node.NameColon != null)
{
return true;
}
}
}
}
return false;
}
public static bool IsNumericTypeContext(this SyntaxToken token, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!(token.Parent is MemberAccessExpressionSyntax memberAccessExpression))
{
return false;
}
var typeInfo = semanticModel.GetTypeInfo(memberAccessExpression.Expression, cancellationToken);
return typeInfo.Type.IsNumericType();
}
}
}
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/EditorFeatures/VisualBasicTest/Diagnostics/Suppression/SuppressionTests.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression
Public MustInherit Class VisualBasicSuppressionTests
Inherits AbstractSuppressionDiagnosticTest
Protected Overrides Function GetScriptOptions() As ParseOptions
Return TestOptions.Script
End Function
Protected Overrides Function MassageActions(ByVal actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return actions(0).NestedCodeActions
End Function
Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters
Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)))
End Function
Protected Overrides Function GetLanguage() As String
Return LanguageNames.VisualBasic
End Function
#Region "Pragma disable tests"
Public MustInherit Class VisualBasicPragmaWarningDisableSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 0
End Get
End Property
Public Class CompilerDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirective() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
[|Dim x As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
[|Dim x As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective1() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
[|Dim x _
As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x _
As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
[|Dim x _
As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective2() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
If i < [|j.MaxValue|] AndAlso
i > 0 Then
Console.WriteLine(i)
End If
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
If i < j.MaxValue AndAlso
i > 0 Then
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Console.WriteLine(i)
End If
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
If i < [|j.MaxValue|] AndAlso
i > 0 Then
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Console.WriteLine(i)
End If
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective3() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
If i > 0 AndAlso
i < [|j.MaxValue|] Then
Console.WriteLine(i)
End If
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
If i > 0 AndAlso
i < j.MaxValue Then
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Console.WriteLine(i)
End If
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
If i > 0 AndAlso
i < [|j.MaxValue|] Then
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Console.WriteLine(i)
End If
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective4() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim [|x As Integer|],
y As Integer
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer,
y As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
Dim [|x As Integer|],
y As Integer
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective5() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim x As Integer,
[|y As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer,
y As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
Dim x As Integer,
[|y As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective6() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
Dim x = <root>
<condition value=<%= i < [|j.MaxValue|] %>/>
</root>
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Dim x = <root>
<condition value=<%= i < j.MaxValue %>/>
</root>
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Dim x = <root>
<condition value=<%= i < [|j.MaxValue|] %>/>
</root>
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective7() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(j As Short)
Dim x = From i As Integer In {}
Where i < [|j.MaxValue|]
Select i
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Dim x = From i As Integer In {{}}
Where i < j.MaxValue
Select i
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Dim x = From i As Integer In {}
Where i < [|j.MaxValue|]
Select i
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveWithExistingTrivia() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
' Trivia previous line
[|Dim x As Integer|] ' Trivia same line
' Trivia next line
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
' Trivia previous line
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer ' Trivia same line
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
' Trivia next line
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
' Trivia previous line
#Disable Warning BC42024 ' Unused local variable
[|Dim x As Integer|] ' Trivia same line
#Enable Warning BC42024 ' Unused local variable
' Trivia next line
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionAroundSingleToken() As Task
Dim source = <![CDATA[
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
[|C|]
End Sub
End Module]]>
Dim expected = $"
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
#Disable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title}
C
#Enable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title}
End Sub
End Module"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
#Disable Warning BC40008 ' Type or member is obsolete
[|C|]
#Enable Warning BC40008 ' Type or member is obsolete
End Sub
End Module]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia1() As Task
Dim source = <![CDATA[
Class C
' Comment
' Comment
''' <summary><see [|cref="abc"|]/></summary>
Sub M() ' Comment
End Sub
End Class]]>
Dim expected = $"
Class C
' Comment
' Comment
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
''' <summary><see cref=""abc""/></summary>
Sub M() ' Comment
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
End Sub
End Class"
Dim enableDocCommentProcessing = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)
Await TestAsync(source.Value, expected, enableDocCommentProcessing)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = $"
Class C
' Comment
' Comment
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
''' <summary><see [|cref=""abc""|]/></summary>
Sub M() ' Comment
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
End Sub
End Class"
Await TestMissingAsync(fixedSource,
New TestParameters(enableDocCommentProcessing))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia2() As Task
Dim source = <![CDATA['''[|<summary></summary>|]]]>
Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}
'''<summary></summary>
#Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia3() As Task
Dim source = <![CDATA[ '''[|<summary></summary>|] ]]>
Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}
'''<summary></summary>
#Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia4() As Task
Dim source = <![CDATA[
'''<summary><see [|cref="abc"|]/></summary>
Class C : End Class
]]>
Dim expected = $"
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
'''<summary><see cref=""abc""/></summary>
Class C : End Class
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia5() As Task
Dim source = <![CDATA[class C1 : End Class
'''<summary><see [|cref="abc"|]/></summary>
Class C2 : End Class
Class C3 : End Class]]>
Dim expected = $"class C1 : End Class
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
'''<summary><see cref=""abc""/></summary>
Class C2 : End Class
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
Class C3 : End Class"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia6() As Task
Dim source = <![CDATA[class C1 : End Class
Class C2 : End Class [|'''|]
Class C3 : End Class]]>
Dim expected = $"class C1 : End Class
#Disable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title}
Class C2 : End Class '''
#Enable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title}
Class C3 : End Class"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
End Class
Public Class UserHiddenDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestHiddenDiagnosticCannotBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim i as [|System.Int32|] = 0
Console.WriteLine(i)
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestInfoDiagnosticSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning InfoDiagnostic ' InfoDiagnostic
Class C
#Enable Warning InfoDiagnostic ' InfoDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning InfoDiagnostic ' InfoDiagnostic
[|Class C|]
#Enable Warning InfoDiagnostic ' InfoDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
Public Class DiagnosticWithBadIdSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Protected Overrides ReadOnly Property IncludeNoLocationDiagnostics As Boolean
Get
' Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here.
Return False
End Get
End Property
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("#$DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestDiagnosticWithBadIdSuppressed() As Task
' Diagnostics with bad/invalid ID are not reported.
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserWarningDiagnosticWithNameMatchingKeywordSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("REm", "REm Title", "REm", "REm", DiagnosticSeverity.Warning, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestWarningDiagnosticWithNameMatchingKeywordSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning [REm] ' REm Title
Class C
#Enable Warning [REm] ' REm Title
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning [REm] ' REm Title
[|Class C|]
#Enable Warning [REm] ' REm Title
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
Public Class UserErrorDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.[Error], isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestErrorDiagnosticCanBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning ErrorDiagnostic ' ErrorDiagnostic
Class C
#Enable Warning ErrorDiagnostic ' ErrorDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning ErrorDiagnostic ' ErrorDiagnostic
[|Class C|]
#Enable Warning ErrorDiagnostic ' ErrorDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
End Class
#End Region
#Region "SuppressMessageAttribute tests"
Public MustInherit Class VisualBasicGlobalSuppressMessageSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 1
End Get
End Property
Public Class CompilerDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestCompilerDiagnosticsCannotBeSuppressed() As Task
Dim source = <![CDATA[
Class Class1
Sub Method()
[|Dim x|]
End Sub
End Class]]>
Await TestActionCountAsync(source.Value, 1)
End Function
End Class
Public Class UserHiddenDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestHiddenDiagnosticsCannotBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
Class Class1
Sub Method()
[|Dim x As System.Int32 = 0|]
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Select Case context.Node.Kind()
Case SyntaxKind.ClassStatement
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.NamespaceStatement
Dim ns = DirectCast(context.Node, NamespaceStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation()))
Exit Select
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(context.Node, MethodStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.PropertyStatement
Dim p = DirectCast(context.Node, PropertyStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.FieldDeclaration
Dim f = DirectCast(context.Node, FieldDeclarationSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation()))
Exit Select
Case SyntaxKind.EventStatement
Dim e = DirectCast(context.Node, EventStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation()))
Exit Select
End Select
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType() As Task
Dim source = <![CDATA[
Imports System
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")>
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNamespace() As Task
Dim source = <![CDATA[
Imports System
[|Namespace N|]
Class Class1
Sub Method()
Dim x
End Sub
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")>
"
Await TestInRegularAndScriptAsync(source.Value, expected, index:=1)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")>
[|Namespace N|]
Class Class1
Sub Method()
Dim x
End Sub
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnTypeInsideNamespace() As Task
Dim source = <![CDATA[
Imports System
Namespace N1
Namespace N2
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Namespace
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")>
Namespace N1
Namespace N2
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Namespace
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNestedType() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")>
Namespace N
Class Generic(Of T)
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method()
Dim x
End Sub|]
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method()
Dim x
End Sub|]
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnOverloadedMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(y as Integer, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(y as Integer, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnGenericMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(Of U)(y as U, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(Of U)(y as U, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnProperty() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic
Private Class C
[|Private ReadOnly Property P() As Integer|]
Get
Dim x As Integer = 0
End Get
End Property
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")>
Namespace N
Class Generic
Private Class C
[|Private ReadOnly Property P() As Integer|]
Get
Dim x As Integer = 0
End Get
End Property
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnField() As Task
Dim source = <![CDATA[
Imports System
Class C
[|Private ReadOnly F As Integer|]
End Class]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")>
Class C
[|Private ReadOnly F As Integer|]
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnEvent() As Task
Dim source = <![CDATA[
Imports System
Public Class SampleEventArgs
Public Sub New(s As String)
Text = s
End Sub
Public Property Text() As [String]
Get
Return m_Text
End Get
Private Set
m_Text = Value
End Set
End Property
Private m_Text As [String]
End Class
Class C
' Declare the delegate (if using non-generic pattern).
Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs)
' Declare the event.
[|Public Custom Event SampleEvent As SampleEventHandler|]
AddHandler(ByVal value As SampleEventHandler)
End AddHandler
RemoveHandler(ByVal value As SampleEventHandler)
End RemoveHandler
End Event
End Class]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")>
Public Class SampleEventArgs
Public Sub New(s As String)
Text = s
End Sub
Public Property Text() As [String]
Get
Return m_Text
End Get
Private Set
m_Text = Value
End Set
End Property
Private m_Text As [String]
End Class
Class C
' Declare the delegate (if using non-generic pattern).
Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs)
' Declare the event.
[|Public Custom Event SampleEvent As SampleEventHandler|]
AddHandler(ByVal value As SampleEventHandler)
End AddHandler
RemoveHandler(ByVal value As SampleEventHandler)
End RemoveHandler
End Event
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument() As Task
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument2() As Task
' Own custom file named GlobalSuppressions.cs
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' My own file named GlobalSuppressions.vb
Class Class3
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument3() As Task
' Own custom file named GlobalSuppressions.vb + existing GlobalSuppressions2.vb with global suppressions
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' My own file named GlobalSuppressions.vb
Class Class3
End Class
]]>
</Document>
<Document FilePath="GlobalSuppressions2.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() As Task
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected = $"
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
End Class
End Class
Public MustInherit Class VisualBasicLocalSuppressMessageSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 2
End Get
End Property
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicLocalSuppressMessageSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Select Case context.Node.Kind()
Case SyntaxKind.ClassStatement
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.NamespaceStatement
Dim ns = DirectCast(context.Node, NamespaceStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation()))
Exit Select
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(context.Node, MethodStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.PropertyStatement
Dim p = DirectCast(context.Node, PropertyStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.FieldDeclaration
Dim f = DirectCast(context.Node, FieldDeclarationSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation()))
Exit Select
Case SyntaxKind.EventStatement
Dim e = DirectCast(context.Node, EventStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation()))
Exit Select
End Select
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType() As Task
Dim source = <![CDATA[
Imports System
' Some Trivia
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType2() As Task
' Type already has attributes.
Dim source = <![CDATA[
Imports System
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")>
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")>
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType3() As Task
' Type has structured trivia.
Dim source = <![CDATA[
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType4() As Task
' Type has structured trivia and attributes.
Dim source = <![CDATA[
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
<Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")>
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
<Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")>
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnTypeInsideNamespace() As Task
Dim source = <![CDATA[
Imports System
Namespace N
' Some Trivia
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
End Namespace]]>
Dim expected = $"
Imports System
Namespace N
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
End Namespace"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNestedType() As Task
Dim source = <![CDATA[
Imports System
Class Generic(Of T)
' Some Trivia
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
End Class]]>
Dim expected = $"
Imports System
Class Generic(Of T)
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnMethod() As Task
Dim source = <![CDATA[
Imports System
Class Generic(Of T)
Class C
' Some Trivia
[|Sub Method()
Dim x
End Sub|]
End Class
End Class]]>
Dim expected = $"
Imports System
Class Generic(Of T)
Class C
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Sub Method()
Dim x
End Sub
End Class
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Sub Method()", "[|Sub Method()|]")
Await TestMissingAsync(fixedSource)
End Function
End Class
End Class
#End Region
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.SimplifyTypeNames
Imports Microsoft.CodeAnalysis.VisualBasic.CodeFixes.Suppression
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.Suppression
Public MustInherit Class VisualBasicSuppressionTests
Inherits AbstractSuppressionDiagnosticTest
Protected Overrides Function GetScriptOptions() As ParseOptions
Return TestOptions.Script
End Function
Protected Overrides Function MassageActions(ByVal actions As ImmutableArray(Of CodeAction)) As ImmutableArray(Of CodeAction)
Return actions(0).NestedCodeActions
End Function
Protected Overrides Function SetParameterDefaults(parameters As TestParameters) As TestParameters
Return parameters.WithCompilationOptions(If(parameters.compilationOptions, New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary)))
End Function
Protected Overrides Function GetLanguage() As String
Return LanguageNames.VisualBasic
End Function
#Region "Pragma disable tests"
Public MustInherit Class VisualBasicPragmaWarningDisableSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 0
End Get
End Property
Public Class CompilerDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirective() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
[|Dim x As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
[|Dim x As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective1() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
[|Dim x _
As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x _
As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
[|Dim x _
As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective2() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
If i < [|j.MaxValue|] AndAlso
i > 0 Then
Console.WriteLine(i)
End If
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
If i < j.MaxValue AndAlso
i > 0 Then
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Console.WriteLine(i)
End If
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
If i < [|j.MaxValue|] AndAlso
i > 0 Then
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Console.WriteLine(i)
End If
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective3() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
If i > 0 AndAlso
i < [|j.MaxValue|] Then
Console.WriteLine(i)
End If
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
If i > 0 AndAlso
i < j.MaxValue Then
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Console.WriteLine(i)
End If
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
If i > 0 AndAlso
i < [|j.MaxValue|] Then
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Console.WriteLine(i)
End If
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective4() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim [|x As Integer|],
y As Integer
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer,
y As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
Dim [|x As Integer|],
y As Integer
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective5() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim x As Integer,
[|y As Integer|]
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer,
y As Integer
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
#Disable Warning BC42024 ' Unused local variable
Dim x As Integer,
[|y As Integer|]
#Enable Warning BC42024 ' Unused local variable
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective6() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
Dim x = <root>
<condition value=<%= i < [|j.MaxValue|] %>/>
</root>
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Dim x = <root>
<condition value=<%= i < j.MaxValue %>/>
</root>
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(i As Integer, j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Dim x = <root>
<condition value=<%= i < [|j.MaxValue|] %>/>
</root>
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestMultilineStatementPragmaWarningDirective7() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method(j As Short)
Dim x = From i As Integer In {}
Where i < [|j.MaxValue|]
Select i
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method(j As Short)
#Disable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
Dim x = From i As Integer In {{}}
Where i < j.MaxValue
Select i
#Enable Warning BC42025 ' {VBResources.WRN_SharedMemberThroughInstance_Title}
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method(j As Short)
#Disable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
Dim x = From i As Integer In {}
Where i < [|j.MaxValue|]
Select i
#Enable Warning BC42025 ' Access of shared member, constant member, enum member or nested type through an instance
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveWithExistingTrivia() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
' Trivia previous line
[|Dim x As Integer|] ' Trivia same line
' Trivia next line
End Sub
End Class]]>
Dim expected = $"
Imports System
Class C
Sub Method()
' Trivia previous line
#Disable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
Dim x As Integer ' Trivia same line
#Enable Warning BC42024 ' {VBResources.WRN_UnusedLocal_Title}
' Trivia next line
End Sub
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
Class C
Sub Method()
' Trivia previous line
#Disable Warning BC42024 ' Unused local variable
[|Dim x As Integer|] ' Trivia same line
#Enable Warning BC42024 ' Unused local variable
' Trivia next line
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(970129, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/970129")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionAroundSingleToken() As Task
Dim source = <![CDATA[
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
[|C|]
End Sub
End Module]]>
Dim expected = $"
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
#Disable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title}
C
#Enable Warning BC40008 ' {VBResources.WRN_UseOfObsoleteSymbolNoMessage1_Title}
End Sub
End Module"
Await TestAsync(source.Value, expected)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
<Obsolete>
Class C
End Class
Module Module1
Sub Main
#Disable Warning BC40008 ' Type or member is obsolete
[|C|]
#Enable Warning BC40008 ' Type or member is obsolete
End Sub
End Module]]>
Await TestMissingAsync(fixedSource.Value)
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia1() As Task
Dim source = <![CDATA[
Class C
' Comment
' Comment
''' <summary><see [|cref="abc"|]/></summary>
Sub M() ' Comment
End Sub
End Class]]>
Dim expected = $"
Class C
' Comment
' Comment
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
''' <summary><see cref=""abc""/></summary>
Sub M() ' Comment
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
End Sub
End Class"
Dim enableDocCommentProcessing = VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose)
Await TestAsync(source.Value, expected, enableDocCommentProcessing)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = $"
Class C
' Comment
' Comment
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
''' <summary><see [|cref=""abc""|]/></summary>
Sub M() ' Comment
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
End Sub
End Class"
Await TestMissingAsync(fixedSource,
New TestParameters(enableDocCommentProcessing))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia2() As Task
Dim source = <![CDATA['''[|<summary></summary>|]]]>
Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}
'''<summary></summary>
#Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia3() As Task
Dim source = <![CDATA[ '''[|<summary></summary>|] ]]>
Dim expected = $"#Disable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}
'''<summary></summary>
#Enable Warning BC42312 ' {VBResources.WRN_XMLDocWithoutLanguageElement_Title}"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia4() As Task
Dim source = <![CDATA[
'''<summary><see [|cref="abc"|]/></summary>
Class C : End Class
]]>
Dim expected = $"
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
'''<summary><see cref=""abc""/></summary>
Class C : End Class
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia5() As Task
Dim source = <![CDATA[class C1 : End Class
'''<summary><see [|cref="abc"|]/></summary>
Class C2 : End Class
Class C3 : End Class]]>
Dim expected = $"class C1 : End Class
#Disable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
'''<summary><see cref=""abc""/></summary>
Class C2 : End Class
#Enable Warning BC42309 ' {VBResources.WRN_XMLDocCrefAttributeNotFound1_Title}
Class C3 : End Class"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
<WorkItem(1066576, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1066576")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestPragmaWarningDirectiveAroundTrivia6() As Task
Dim source = <![CDATA[class C1 : End Class
Class C2 : End Class [|'''|]
Class C3 : End Class]]>
Dim expected = $"class C1 : End Class
#Disable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title}
Class C2 : End Class '''
#Enable Warning BC42302 ' {VBResources.WRN_XMLDocNotFirstOnLine_Title}
Class C3 : End Class"
Await TestAsync(source.Value, expected, VisualBasicParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose))
End Function
End Class
Public Class UserHiddenDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestHiddenDiagnosticCannotBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
Class C
Sub Method()
Dim i as [|System.Int32|] = 0
Console.WriteLine(i)
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestInfoDiagnosticSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning InfoDiagnostic ' InfoDiagnostic
Class C
#Enable Warning InfoDiagnostic ' InfoDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning InfoDiagnostic ' InfoDiagnostic
[|Class C|]
#Enable Warning InfoDiagnostic ' InfoDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
Public Class DiagnosticWithBadIdSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Protected Overrides ReadOnly Property IncludeNoLocationDiagnostics As Boolean
Get
' Analyzer driver generates a no-location analyzer exception diagnostic, which we don't intend to test here.
Return False
End Get
End Property
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("#$DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", "DiagnosticWithBadId", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestDiagnosticWithBadIdSuppressed() As Task
' Diagnostics with bad/invalid ID are not reported.
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserWarningDiagnosticWithNameMatchingKeywordSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("REm", "REm Title", "REm", "REm", DiagnosticSeverity.Warning, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestWarningDiagnosticWithNameMatchingKeywordSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning [REm] ' REm Title
Class C
#Enable Warning [REm] ' REm Title
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning [REm] ' REm Title
[|Class C|]
#Enable Warning [REm] ' REm Title
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
Public Class UserErrorDiagnosticSuppressionTests
Inherits VisualBasicPragmaWarningDisableSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", "ErrorDiagnostic", DiagnosticSeverity.[Error], isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement)
End Sub
Public Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestErrorDiagnosticCanBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
[|Class C|]
Sub Method()
End Sub
End Class]]>
Dim expected = <![CDATA[
Imports System
#Disable Warning ErrorDiagnostic ' ErrorDiagnostic
Class C
#Enable Warning ErrorDiagnostic ' ErrorDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestAsync(source.Value, expected.Value)
' Also verify that the added directive does indeed suppress the diagnostic.
Dim fixedSource = <![CDATA[
Imports System
#Disable Warning ErrorDiagnostic ' ErrorDiagnostic
[|Class C|]
#Enable Warning ErrorDiagnostic ' ErrorDiagnostic
Sub Method()
End Sub
End Class]]>
Await TestMissingAsync(fixedSource.Value)
End Function
End Class
End Class
#End Region
#Region "SuppressMessageAttribute tests"
Public MustInherit Class VisualBasicGlobalSuppressMessageSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 1
End Get
End Property
Public Class CompilerDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return Tuple.Create(Of DiagnosticAnalyzer, IConfigurationFixProvider)(Nothing, New VisualBasicSuppressionCodeFixProvider())
End Function
<WorkItem(730770, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730770")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestCompilerDiagnosticsCannotBeSuppressed() As Task
Dim source = <![CDATA[
Class Class1
Sub Method()
[|Dim x|]
End Sub
End Class]]>
Await TestActionCountAsync(source.Value, 1)
End Function
End Class
Public Class UserHiddenDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New VisualBasicSimplifyTypeNamesDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestHiddenDiagnosticsCannotBeSuppressed() As Task
Dim source = <![CDATA[
Imports System
Class Class1
Sub Method()
[|Dim x As System.Int32 = 0|]
End Sub
End Class]]>
Await TestMissingAsync(source.Value)
End Function
End Class
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicGlobalSuppressMessageSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Select Case context.Node.Kind()
Case SyntaxKind.ClassStatement
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.NamespaceStatement
Dim ns = DirectCast(context.Node, NamespaceStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation()))
Exit Select
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(context.Node, MethodStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.PropertyStatement
Dim p = DirectCast(context.Node, PropertyStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.FieldDeclaration
Dim f = DirectCast(context.Node, FieldDeclarationSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation()))
Exit Select
Case SyntaxKind.EventStatement
Dim e = DirectCast(context.Node, EventStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation()))
Exit Select
End Select
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType() As Task
Dim source = <![CDATA[
Imports System
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class1"")>
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNamespace() As Task
Dim source = <![CDATA[
Imports System
[|Namespace N|]
Class Class1
Sub Method()
Dim x
End Sub
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")>
"
Await TestInRegularAndScriptAsync(source.Value, expected, index:=1)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""namespace"", Target:=""~N:N"")>
[|Namespace N|]
Class Class1
Sub Method()
Dim x
End Sub
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnTypeInsideNamespace() As Task
Dim source = <![CDATA[
Imports System
Namespace N1
Namespace N2
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Namespace
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N1.N2.Class1"")>
Namespace N1
Namespace N2
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Namespace
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNestedType() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:N.Generic`1.Class1"")>
Namespace N
Class Generic(Of T)
[|Class Class1|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method()
Dim x
End Sub|]
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method()
Dim x
End Sub|]
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnOverloadedMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(y as Integer, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method(System.Int32,System.Int32@)"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(y as Integer, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnGenericMethod() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(Of U)(y as U, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~M:N.Generic`1.Class1.Method``1(``0,System.Int32@)"")>
Namespace N
Class Generic(Of T)
Class Class1
[|Sub Method(Of U)(y as U, ByRef z as Integer)
Dim x
End Sub|]
Sub Method()
Dim x
End Sub
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnProperty() As Task
Dim source = <![CDATA[
Imports System
Namespace N
Class Generic
Private Class C
[|Private ReadOnly Property P() As Integer|]
Get
Dim x As Integer = 0
End Get
End Property
End Class
End Class
End Namespace]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~P:N.Generic.C.P"")>
Namespace N
Class Generic
Private Class C
[|Private ReadOnly Property P() As Integer|]
Get
Dim x As Integer = 0
End Get
End Property
End Class
End Class
End Namespace"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnField() As Task
Dim source = <![CDATA[
Imports System
Class C
[|Private ReadOnly F As Integer|]
End Class]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~F:C.F"")>
Class C
[|Private ReadOnly F As Integer|]
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnEvent() As Task
Dim source = <![CDATA[
Imports System
Public Class SampleEventArgs
Public Sub New(s As String)
Text = s
End Sub
Public Property Text() As [String]
Get
Return m_Text
End Get
Private Set
m_Text = Value
End Set
End Property
Private m_Text As [String]
End Class
Class C
' Declare the delegate (if using non-generic pattern).
Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs)
' Declare the event.
[|Public Custom Event SampleEvent As SampleEventHandler|]
AddHandler(ByVal value As SampleEventHandler)
End AddHandler
RemoveHandler(ByVal value As SampleEventHandler)
End RemoveHandler
End Event
End Class]]>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")>
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = $"
Imports System
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""member"", Target:=""~E:C.SampleEvent"")>
Public Class SampleEventArgs
Public Sub New(s As String)
Text = s
End Sub
Public Property Text() As [String]
Get
Return m_Text
End Get
Private Set
m_Text = Value
End Set
End Property
Private m_Text As [String]
End Class
Class C
' Declare the delegate (if using non-generic pattern).
Public Delegate Sub SampleEventHandler(sender As Object, e As SampleEventArgs)
' Declare the event.
[|Public Custom Event SampleEvent As SampleEventHandler|]
AddHandler(ByVal value As SampleEventHandler)
End AddHandler
RemoveHandler(ByVal value As SampleEventHandler)
End RemoveHandler
End Event
End Class"
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument() As Task
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument2() As Task
' Own custom file named GlobalSuppressions.cs
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' My own file named GlobalSuppressions.vb
Class Class3
End Class
]]>
</Document>
</Project>
</Workspace>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithExistingGlobalSuppressionsDocument3() As Task
' Own custom file named GlobalSuppressions.vb + existing GlobalSuppressions2.vb with global suppressions
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
' My own file named GlobalSuppressions.vb
Class Class3
End Class
]]>
</Document>
<Document FilePath="GlobalSuppressions2.vb"><![CDATA[' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected =
$"' This file is used by Code Analysis to maintain SuppressMessage
' attributes that are applied to this project.
' Project-level suppressions either have no target or are given
' a specific target and scoped to a namespace, type, member, etc.
Imports System.Diagnostics.CodeAnalysis
<Assembly: System.Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionWithUsingDirectiveInExistingGlobalSuppressionsDocument() As Task
Dim source =
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="CurrentDocument.vb"><![CDATA[
Imports System
Class Class1
End Class
[|Class Class2|]
End Class]]>
</Document>
<Document FilePath="GlobalSuppressions.vb"><![CDATA[
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage("InfoDiagnostic", "InfoDiagnostic:InfoDiagnostic", Justification:="<Pending>", Scope:="type", Target:="Class1")>
]]>
</Document>
</Project>
</Workspace>
Dim expected = $"
Imports System.Diagnostics.CodeAnalysis
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""<Pending>"", Scope:=""type"", Target:=""Class1"")>
<Assembly: SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"", Scope:=""type"", Target:=""~T:Class2"")>
"
Await TestAsync(source.ToString(), expected)
End Function
End Class
End Class
Public MustInherit Class VisualBasicLocalSuppressMessageSuppressionTests
Inherits VisualBasicSuppressionTests
Protected NotOverridable Overrides ReadOnly Property CodeActionIndex() As Integer
Get
Return 2
End Get
End Property
Public Class UserInfoDiagnosticSuppressionTests
Inherits VisualBasicLocalSuppressMessageSuppressionTests
Private Class UserDiagnosticAnalyzer
Inherits DiagnosticAnalyzer
Private ReadOnly _descriptor As New DiagnosticDescriptor("InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", "InfoDiagnostic", DiagnosticSeverity.Info, isEnabledByDefault:=True)
Public Overrides ReadOnly Property SupportedDiagnostics() As ImmutableArray(Of DiagnosticDescriptor)
Get
Return ImmutableArray.Create(_descriptor)
End Get
End Property
Public Overrides Sub Initialize(context As AnalysisContext)
context.RegisterSyntaxNodeAction(AddressOf AnalyzeNode, SyntaxKind.ClassStatement, SyntaxKind.NamespaceStatement, SyntaxKind.SubStatement, SyntaxKind.FunctionStatement, SyntaxKind.PropertyStatement, SyntaxKind.FieldDeclaration, SyntaxKind.EventStatement)
End Sub
Private Sub AnalyzeNode(context As SyntaxNodeAnalysisContext)
Select Case context.Node.Kind()
Case SyntaxKind.ClassStatement
Dim classDecl = DirectCast(context.Node, ClassStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, classDecl.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.NamespaceStatement
Dim ns = DirectCast(context.Node, NamespaceStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, ns.Name.GetLocation()))
Exit Select
Case SyntaxKind.SubStatement, SyntaxKind.FunctionStatement
Dim method = DirectCast(context.Node, MethodStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, method.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.PropertyStatement
Dim p = DirectCast(context.Node, PropertyStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, p.Identifier.GetLocation()))
Exit Select
Case SyntaxKind.FieldDeclaration
Dim f = DirectCast(context.Node, FieldDeclarationSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, f.Declarators.First().Names.First.GetLocation()))
Exit Select
Case SyntaxKind.EventStatement
Dim e = DirectCast(context.Node, EventStatementSyntax)
context.ReportDiagnostic(Diagnostic.Create(_descriptor, e.Identifier.GetLocation()))
Exit Select
End Select
End Sub
End Class
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)
Return New Tuple(Of DiagnosticAnalyzer, IConfigurationFixProvider)(New UserDiagnosticAnalyzer(), New VisualBasicSuppressionCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType() As Task
Dim source = <![CDATA[
Imports System
' Some Trivia
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType2() As Task
' Type already has attributes.
Dim source = <![CDATA[
Imports System
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")>
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")>
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType3() As Task
' Type has structured trivia.
Dim source = <![CDATA[
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnSimpleType4() As Task
' Type has structured trivia and attributes.
Dim source = <![CDATA[
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
<Diagnostics.CodeAnalysis.SuppressMessage("SomeOtherDiagnostic", "SomeOtherDiagnostic:Title", Justification:="<Pending>")>
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
]]>
Dim expected = $"
Imports System
' Some Trivia
''' <summary>
''' My custom type
''' </summary>
<Diagnostics.CodeAnalysis.SuppressMessage(""SomeOtherDiagnostic"", ""SomeOtherDiagnostic:Title"", Justification:=""<Pending>"")>
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnTypeInsideNamespace() As Task
Dim source = <![CDATA[
Imports System
Namespace N
' Some Trivia
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
End Namespace]]>
Dim expected = $"
Imports System
Namespace N
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
End Namespace"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnNestedType() As Task
Dim source = <![CDATA[
Imports System
Class Generic(Of T)
' Some Trivia
[|Class C|]
Sub Method()
Dim x
End Sub
End Class
End Class]]>
Dim expected = $"
Imports System
Class Generic(Of T)
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Class C
Sub Method()
Dim x
End Sub
End Class
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Class C", "[|Class C|]")
Await TestMissingAsync(fixedSource)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsSuppression)>
Public Async Function TestSuppressionOnMethod() As Task
Dim source = <![CDATA[
Imports System
Class Generic(Of T)
Class C
' Some Trivia
[|Sub Method()
Dim x
End Sub|]
End Class
End Class]]>
Dim expected = $"
Imports System
Class Generic(Of T)
Class C
' Some Trivia
<Diagnostics.CodeAnalysis.SuppressMessage(""InfoDiagnostic"", ""InfoDiagnostic:InfoDiagnostic"", Justification:=""{FeaturesResources.Pending}"")>
Sub Method()
Dim x
End Sub
End Class
End Class"
Await TestAsync(source.Value, expected)
' Also verify that the added attribute does indeed suppress the diagnostic.
Dim fixedSource = expected.Replace("Sub Method()", "[|Sub Method()|]")
Await TestMissingAsync(fixedSource)
End Function
End Class
End Class
#End Region
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,012 | Generalize rude edit messages to be applicable to both Hot Reload and EnC | Implements https://github.com/dotnet/roslyn/issues/52018 | tmat | 2021-07-21T17:31:52Z | 2021-07-22T12:12:12Z | 8551591d07ec3e29aaaee5260980b0265814159f | 911be131f6e14b71880244520c1a9c4bffb83750 | Generalize rude edit messages to be applicable to both Hot Reload and EnC. Implements https://github.com/dotnet/roslyn/issues/52018 | ./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Core.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
#if NETCOREAPP
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Loader;
namespace Microsoft.CodeAnalysis
{
internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader
{
private AssemblyLoadContext _loadContext;
protected override Assembly LoadFromPathImpl(string fullPath)
{
//.NET Native doesn't support AssemblyLoadContext.GetLoadContext.
// Initializing the _loadContext in the .ctor would cause
// .NET Native builds to fail because the .ctor is called.
// However, LoadFromPathImpl is never called in .NET Native, so
// we do a lazy initialization here to make .NET Native builds happy.
if (_loadContext == null)
{
AssemblyLoadContext loadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly);
if (System.Threading.Interlocked.CompareExchange(ref _loadContext, loadContext, null) == null)
{
_loadContext.Resolving += (context, name) =>
{
Debug.Assert(ReferenceEquals(context, _loadContext));
return Load(name.FullName);
};
}
}
return LoadImpl(fullPath);
}
protected virtual Assembly LoadImpl(string fullPath) => _loadContext.LoadFromAssemblyPath(fullPath);
}
}
#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
#if NETCOREAPP
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Loader;
namespace Microsoft.CodeAnalysis
{
internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader
{
private AssemblyLoadContext _loadContext;
protected override Assembly LoadFromPathImpl(string fullPath)
{
//.NET Native doesn't support AssemblyLoadContext.GetLoadContext.
// Initializing the _loadContext in the .ctor would cause
// .NET Native builds to fail because the .ctor is called.
// However, LoadFromPathImpl is never called in .NET Native, so
// we do a lazy initialization here to make .NET Native builds happy.
if (_loadContext == null)
{
AssemblyLoadContext loadContext = AssemblyLoadContext.GetLoadContext(typeof(DefaultAnalyzerAssemblyLoader).GetTypeInfo().Assembly);
if (System.Threading.Interlocked.CompareExchange(ref _loadContext, loadContext, null) == null)
{
_loadContext.Resolving += (context, name) =>
{
Debug.Assert(ReferenceEquals(context, _loadContext));
return Load(name.FullName);
};
}
}
return LoadImpl(fullPath);
}
protected virtual Assembly LoadImpl(string fullPath) => _loadContext.LoadFromAssemblyPath(fullPath);
}
}
#endif
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/AddUsing/AddUsingTests.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.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing
{
[Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public partial class AddUsingTests : AbstractAddUsingTests
{
public AddUsingTests(ITestOutputHelper logger)
: base(logger)
{
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost)
{
await TestAsync(
@"
namespace N;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
using System.Collections;
namespace N;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost)
{
await TestAsync(
@"
namespace N;
using System;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
namespace N;
using System;
using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")]
public async Task TestAddImportWithCaseChange(TestHost testHost)
{
await TestAsync(
@"namespace N1
{
public class TextBox
{
}
}
class Class1 : [|Textbox|]
{
}",
@"using N1;
namespace N1
{
public class TextBox
{
}
}
class Class1 : TextBox
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces2(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}",
testHost, index: 1);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithNoArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithCorrectArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Fact]
public async Task TestGenericWithWrongArgs1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string, bool>|] Method()
{
Goo();
}
}");
}
[Fact]
public async Task TestGenericWithWrongArgs2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Goo();
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestGenericInLocalDeclaration(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
[|List<int>|] a = new List<int>();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> a = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericItemType(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<Int32> l;
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateWithExistingUsings(TestHost testHost)
{
await TestAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespace(TestHost testHost)
{
await TestAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"using System.Collections.Generic;
namespace N
{
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespaceWithUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Fact]
public async Task TestExistingUsing_ActionCount()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
count: 1);
}
[Theory]
[CombinatorialData]
public async Task TestExistingUsing(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
void Method(IList<int> args)
{
args.[|Where|]() }
}",
@"using System.Collections.Generic;
using System.Linq;
class Class
{
void Method(IList<int> args)
{
args.Where() }
}", testHost);
}
[Fact]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForNormalExtensionMethod()
{
await TestAsync(
@"class Class
{
void Method(Class args)
{
args.[|Where|]() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
@"using N;
class Class
{
void Method(Class args)
{
args.Where() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
parseOptions: Options.Regular);
}
[Theory]
[CombinatorialData]
public async Task TestOnEnum(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"using A;
class Class
{
void Goo()
{
var a = Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnClassInheritance(TestHost testHost)
{
await TestAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"using A;
class Class : Class2
{
}
namespace A
{
class Class2
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnImplementedInterface(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|]
{
}
namespace A
{
interface IGoo
{
}
}",
@"using A;
class Class : IGoo
{
}
namespace A
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAllInBaseList(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
await TestAsync(
@"using B;
class Class : IGoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using A;
using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeUnexpanded(TestHost testHost)
{
await TestAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"using System;
[Obsolete]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeExpanded(TestHost testHost)
{
await TestAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"using System;
[ObsoleteAttribute]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
public async Task TestAfterNew(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> l;
l = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestArgumentsInMethodCall(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"using System;
class Class
{
void Test()
{
Console.WriteLine(DateTime.Today);
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestCallSiteArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"using System;
class Class
{
void Test(DateTime dt)
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsePartialClass(TestHost testHost)
{
await TestAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"using B;
namespace A
{
public class Class
{
PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericClassInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"using A.B;
namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
GenericClass<int> c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestExtensionMethods(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
values.[|Where|](i => i > 1);
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
values.Where(i => i > 1);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestQueryPatterns(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = [|from v in values
where v > 1
select v + 10|];
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = from v in values
where v > 1
select v + 10;
}
}", testHost);
}
// Tests for Insertion Order
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using C;
using D;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using C;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using C;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using D;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using D;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.Y;
using B.X;
using B.A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.Y;
using B.X;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
// System on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings1(TestHost testHost)
{
await TestAsync(
@"using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using System.Collections.Generic;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings3(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"
using C;
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using B;
using System;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System.Collections.Generic;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B;
using A;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using B;
using A;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings1(TestHost testHost)
{
await TestAsync(
@"using A.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings2(TestHost testHost)
{
await TestAsync(
@"using System.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsingsWithComments(TestHost testHost)
{
await TestAsync(
@"using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
// System Not on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost)
{
await TestAsync(
@"
using C;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings5(TestHost testHost)
{
await TestAsync(
@"using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings4(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false));
}
[Fact]
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
public async Task TestAddUsingForNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")]
public async Task TestAddUsingForFieldWithFormatting(TestHost testHost)
{
await TestAsync(
@"class C { [|DateTime|] t; }",
@"using System;
class C { DateTime t; }", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")]
public async Task BugFix5688(TestHost testHost)
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ",
@"using System;
class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost);
}
[Fact]
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console;
using System.Linq.Expressions;
WriteLine(Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective1(TestHost testHost)
{
await TestAsync(
@"#define goo
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective2(TestHost testHost)
{
await TestAsync(
@"#define goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective3(TestHost testHost)
{
await TestAsync(
@"#define goo
/// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
/// Goo
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective4(TestHost testHost)
{
await TestAsync(
@"#define goo
// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
// Goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExistingBanner(TestHost testHost)
{
await TestAsync(
@"// Banner
// Banner
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"// Banner
// Banner
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias1(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias2(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
using System.Collections;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Fact]
public async Task TestWithReferenceDirective()
{
var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>()
{
{ "exprs", AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference() }
});
await TestAsync(
@"#r ""exprs""
[|Expression|]",
@"#r ""exprs""
using System.Linq.Expressions;
Expression",
GetScriptOptions(),
TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver));
}
[Theory]
[CombinatorialData]
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
public async Task TestAssemblyAttribute(TestHost testHost)
{
await TestAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Project"")]", testHost);
}
[Fact]
public async Task TestDoNotAddIntoHiddenRegion()
{
await TestMissingInRegularAndScriptAsync(
@"#line hidden
using System.Collections.Generic;
#line default
class Program
{
void Main()
{
[|DateTime|] d;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddToVisibleRegion(TestHost testHost)
{
await TestAsync(
@"#line default
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
[|DateTime|] d;
#line hidden
}
}
#line default",
@"#line default
using System;
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
DateTime d;
#line hidden
}
}
#line default", testHost);
}
[Fact]
[WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")]
public async Task TestVenusGeneration1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void Goo()
{
#line 1 ""Default.aspx""
using (new [|StreamReader|]())
{
#line default
#line hidden
}
}");
}
[Fact]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute_ActionCount()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 2);
}
[Theory]
[CombinatorialData]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute(TestHost testHost)
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestAsync(
input,
@"using System.Runtime.InteropServices;
[ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost);
}
[Fact]
[WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")]
public async Task TestNotOnOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"namespace ConsoleApplication1
{
class Program
{
void Main()
{
var test = new [|Test|]("""");
}
}
class Test
{
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(17020, "DevDiv_Projects/Roslyn")]
public async Task TestAddUsingForGenericArgument(TestHost testHost)
{
await TestAsync(
@"namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<[|IEnumerable<int>|]>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}",
@"using System.Collections.Generic;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<IEnumerable<int>>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
public async Task ShouldTriggerOnCS0308(TestHost testHost)
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
IEnumerable<int> f;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")]
public async Task TestConflictedInaccessibleType(TestHost testHost)
{
await TestAsync(
@"using System.Diagnostics;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
[|Log|] }
}",
@"using System.Diagnostics;
using N;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
Log }
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")]
public async Task TestConflictedAttributeName(TestHost testHost)
{
await TestAsync(
@"[[|Description|]]
class Description
{
}",
@"using System.ComponentModel;
[Description]
class Description
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")]
public async Task TestConflictedGenericName(TestHost testHost)
{
await TestAsync(
@"using Task = System.AccessViolationException;
class X
{
[|Task<X> x;|]
}",
@"using System.Threading.Tasks;
using Task = System.AccessViolationException;
class X
{
Task<X> x;
}", testHost);
}
[Fact]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport_ActionCount()
{
await TestActionCountInAllFixesAsync(
@"class C
{
void M(P p)
{
[|Console|]
}
static void Main(string[] args)
{
}
}", count: 1);
}
[Theory]
[CombinatorialData]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport(TestHost testHost)
{
await TestAsync(
@"class C
{
void M(P p)
{
[|Console|] }
static void Main(string[] args)
{
}
}",
@"using System;
class C
{
void M(P p)
{
Console }
static void Main(string[] args)
{
}
}", testHost);
}
[Fact]
[WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")]
public async Task TestNullParentInNode()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class MultiDictionary<K, V> : Dictionary<K, HashSet<V>>
{
void M()
{
new HashSet<V>([|Comparer|]);
}
}");
}
[Fact]
[WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")]
public async Task TestMalformedUsingSection()
{
await TestMissingInRegularAndScriptAsync(
@"[ class Class
{
[|List<|] }");
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost)
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
[|INotifyPropertyChanged.PropertyChanged|]
}
}",
@"using System.ComponentModel;
class Program
{
static void Main(string[] args)
{
INotifyPropertyChanged.PropertyChanged
}
}", testHost);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref2()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref3()
{
var initialText =
@"namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/>
public class MyClass2
{
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator D(MyClass)'/>
public class MyClass2
{
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref4()
{
var initialText =
@"namespace N1
{
public class D { }
}
/// <seealso cref='[|Test(D)|]'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
/// <seealso cref='Test(D)'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType2(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType3(TestHost testHost)
{
await TestAsync(
@"using System;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{
}",
@"using System;
using static Outer.Inner;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType4(TestHost testHost)
{
var initialText =
@"using System;
using Outer;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using Outer;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective1(TestHost testHost)
{
await TestAsync(
@"namespace ns
{
using B = [|Byte|];
}",
@"using System;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective2(TestHost testHost)
{
await TestAsync(
@"using System.Collections;
namespace ns
{
using B = [|Byte|];
}",
@"using System;
using System.Collections;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective3(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
namespace ns3
{
namespace ns
{
using B = [|Byte|];
namespace ns4
{
}
}
}
}",
@"using System;
namespace ns2
{
namespace ns3
{
namespace ns
{
using B = Byte;
namespace ns4
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective4(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = [|Byte|];
}
}
}",
@"namespace ns2
{
using System;
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = Byte;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective5(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System.Collections;
namespace ns
{
using B = [|Byte|];
}
}
}",
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System;
using System.Collections;
namespace ns
{
using B = Byte;
}
}
}", testHost);
}
[Fact]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective6()
{
await TestMissingInRegularAndScriptAsync(
@"using B = [|Byte|];");
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
void Main(C a)
{
C x = a?[|.B()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class E
{
public static C B(this C c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
void Main(C a)
{
C x = a?.B();
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression2(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.[|C()|];
}
public class E
{
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class D
{
public static C.E C(this C.E c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.C();
}
public class E
{
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")]
public async Task TestAmbiguousUsingName(TestHost testHost)
{
await TestAsync(
@"namespace ClassLibrary1
{
using System;
public class SomeTypeUser
{
[|SomeType|] field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}",
@"namespace ClassLibrary1
{
using System;
using global::SubNamespaceName;
public class SomeTypeUser
{
SomeType field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
#endif
class Program
{
static void Main(string[] args)
{
var a = [|File|].OpenRead("""");
}
}",
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.IO;
#endif
class Program
{
static void Main(string[] args)
{
var a = File.OpenRead("""");
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective2(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective3(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective4(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Fact]
public async Task TestInaccessibleExtensionMethod()
{
const string initial = @"
namespace N1
{
public static class C
{
private static bool ExtMethod1(this string arg1)
{
return true;
}
}
}
namespace N2
{
class Program
{
static void Main(string[] args)
{
var x = ""str1"".[|ExtMethod1()|];
}
}
}";
await TestMissingInRegularAndScriptAsync(initial);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForProperty(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.[|Instance|];
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.Instance;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForField(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public B B
{
get
{
return B.[|Instance|];
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using A;
class Program
{
public B B
{
get
{
return B.Instance;
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")]
public async Task TestNameSimplification(TestHost testHost)
{
// Generated using directive must be simplified from "using A.B;" to "using B;" below.
await TestAsync(
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
class T2
{
void Test()
{
Console.WriteLine();
[|T1|] t1;
}
}
}",
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
using A.B;
class T2
{
void Test()
{
Console.WriteLine();
T1 t1;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.[|ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?[|.ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
int i = 0.[|All|]();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
int i = 0.All();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?[|.All|]();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?.All();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified2(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified3(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified4(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified5(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified6(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalUppercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var b = new [|B|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using Uppercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var b = new B();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalLowercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var a = new [|b|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using lowercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var a = new b();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")]
public async Task TestWithExistingIncompatibleExtension(TestHost testHost)
{
await TestAsync(
@"using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.[|Any|]
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}",
@"using System.Linq;
using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.Any
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")]
public async Task TestIncompleteCatchBlockInLambda(TestHost testHost)
{
await TestAsync(
@"class A
{
System.Action a = () => {
try
{
}
catch ([|Exception|]",
@"using System;
class A
{
System.Action a = () => {
try
{
}
catch (Exception", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|]. }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int>. }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda2(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|] }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int> }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda3(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|].
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>.
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda4(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|]
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[Theory]
[CombinatorialData]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost)
{
await TestAsync(
@"using System;
class Test
{
void Goo()
{
Action a = () => {
[|IBindCtx|] };
string a;
}
}",
@"using System;
using System.Runtime.InteropServices.ComTypes;
class Test
{
void Goo()
{
Action a = () => {
IBindCtx };
string a;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")]
public async Task TestExtensionWithIncompatibleInstance(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.[|Write|](new byte[] { 1, 2, 3 });
}
}
}",
@"using System.IO;
using Namespace1;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.Write(new byte[] { 1, 2, 3 });
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")]
public async Task TestFormattingForNamespaceUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
void Main()
{
[|Task<int>|]
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
void Main()
{
Task<int>
}
}
}", testHost);
}
[Fact]
public async Task TestGenericAmbiguityInSameNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace NS
{
class C<T> where T : [|C|].N
{
public class N
{
}
}
}");
}
[Fact]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
class C : [|IEnumerable|]<int>
{
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections.Generic;
class C : IEnumerable<int>
{
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System.Collections;
class C
{
[|DateTime|] d;
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections;
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
[|DateTime|] d;
}
",
@"
using System;
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using C = System.Collections;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"
using System;
using System.Collections.Generic;
namespace N
{
using C = System.Collections;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using System;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst2(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using Microsoft;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost, index: 1);
}
[Fact]
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")]
public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
[|IVsStatusBar|] b;
}
}
}
",
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
using VS;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
IVsStatusbar b;
}
}
}
", testHost);
}
[Fact]
[WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")]
public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression()
{
var code = @"
class C
{
private void GetEvaluationRuleNames()
{
[|IEnumerable|] < Int32 >
return ImmutableArray.CreateRange();
}
}";
await TestActionCountAsync(code, count: 1);
await TestInRegularAndScriptAsync(
code,
@"
using System.Collections.Generic;
class C
{
private void GetEvaluationRuleNames()
{
IEnumerable < Int32 >
return ImmutableArray.CreateRange();
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome1(TestHost testHost)
{
// System is set to be sorted first, but the actual file shows it at the end.
// Keep things sorted, but respect that 'System' is at the end.
await TestAsync(
@"
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome2(TestHost testHost)
{
// System is set to not be sorted first, but the actual file shows it sorted first.
// Keep things sorted, but respect that 'System' is at the beginning.
await TestAsync(
@"
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Fact]
public async Task TestExactMatchNoGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Other|] b;
}
}
", ImmutableArray<string>.Empty);
}
[Fact]
public async Task TestFuzzyMatchGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Otter|] b;
}
}
", WellKnownTagArrays.Namespace);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod1(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|Goo|];
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await Goo;
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod2(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|GetC|]();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await GetC();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(745490, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")]
public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Threading.Tasks;
class C
{
C Instance { get; }
async Task M() => await Instance.[|Foo|]();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}",
@"
namespace A
{
using System;
using System.Threading.Tasks;
using B;
class C
{
C Instance { get; }
async Task M() => await Instance.Foo();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetEnumerator()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in [|Instance|]); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in Instance); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable,
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable, testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetAsyncEnumerator()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetAsyncEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in Instance); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
public async Task KeepUsingsGrouped1(TestHost testHost)
{
await TestAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
[|Goo|]
}
}
namespace Microsoft
{
public class Goo
{
}
}",
@"
using System;
using Microsoft;
class Program
{
static void Main(string[] args)
{
Goo
}
}
namespace Microsoft
{
public class Goo
{
}
}", testHost);
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda1()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte");
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda2()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]() }",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte() }");
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
[Fact]
public async Task TestIncompleteSimpleLambdaExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => [|IBindCtx|]
string a;
}
}",
@"using System.Linq;
using System.Runtime.InteropServices.ComTypes;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => IBindCtx
string a;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
using System.ComponentModel;
namespace ProjectLib
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class Project
{
}
}
</Document>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Never)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost));
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(
options: Option(CompletionOptions.HideAdvancedMembers, true),
testHost: testHost));
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Remote.Testing;
using Microsoft.CodeAnalysis.Tags;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.AddUsing
{
[Trait(Traits.Feature, Traits.Features.CodeActionsAddImport)]
public partial class AddUsingTests : AbstractAddUsingTests
{
public AddUsingTests(ITestOutputHelper logger)
: base(logger)
{
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Outer(TestHost testHost)
{
await TestAsync(
@"
namespace N;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
using System.Collections;
namespace N;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces1_FileScopedNamespace_Inner(TestHost testHost)
{
await TestAsync(
@"
namespace N;
using System;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"
namespace N;
using System;
using System.Collections;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(11241, "https://github.com/dotnet/roslyn/issues/11241")]
public async Task TestAddImportWithCaseChange(TestHost testHost)
{
await TestAsync(
@"namespace N1
{
public class TextBox
{
}
}
class Class1 : [|Textbox|]
{
}",
@"using N1;
namespace N1
{
public class TextBox
{
}
}
class Class1 : TextBox
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestTypeFromMultipleNamespaces2(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}",
testHost, index: 1);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithNoArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericWithCorrectArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Fact]
public async Task TestGenericWithWrongArgs1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string, bool>|] Method()
{
Goo();
}
}");
}
[Fact]
public async Task TestGenericWithWrongArgs2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|List<int, string>|] Method()
{
Goo();
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestGenericInLocalDeclaration(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
[|List<int>|] a = new List<int>();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> a = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericItemType(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
List<[|Int32|]> l;
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<Int32> l;
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateWithExistingUsings(TestHost testHost)
{
await TestAsync(
@"using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}",
@"using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespace(TestHost testHost)
{
await TestAsync(
@"namespace N
{
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"using System.Collections.Generic;
namespace N
{
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenerateInNamespaceWithUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Fact]
public async Task TestExistingUsing_ActionCount()
{
await TestActionCountAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
count: 1);
}
[Theory]
[CombinatorialData]
public async Task TestExistingUsing(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
[|IDictionary|] Method()
{
Goo();
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Class
{
IDictionary Method()
{
Goo();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForGenericExtensionMethod(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Class
{
void Method(IList<int> args)
{
args.[|Where|]() }
}",
@"using System.Collections.Generic;
using System.Linq;
class Class
{
void Method(IList<int> args)
{
args.Where() }
}", testHost);
}
[Fact]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestAddUsingForNormalExtensionMethod()
{
await TestAsync(
@"class Class
{
void Method(Class args)
{
args.[|Where|]() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
@"using N;
class Class
{
void Method(Class args)
{
args.Where() }
}
namespace N
{
static class E
{
public static void Where(this Class c)
{
}
}
}",
parseOptions: Options.Regular);
}
[Theory]
[CombinatorialData]
public async Task TestOnEnum(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
var a = [|Colors|].Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}",
@"using A;
class Class
{
void Goo()
{
var a = Colors.Red;
}
}
namespace A
{
enum Colors
{
Red,
Green,
Blue
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnClassInheritance(TestHost testHost)
{
await TestAsync(
@"class Class : [|Class2|]
{
}
namespace A
{
class Class2
{
}
}",
@"using A;
class Class : Class2
{
}
namespace A
{
class Class2
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestOnImplementedInterface(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|]
{
}
namespace A
{
interface IGoo
{
}
}",
@"using A;
class Class : IGoo
{
}
namespace A
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAllInBaseList(TestHost testHost)
{
await TestAsync(
@"class Class : [|IGoo|], Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
await TestAsync(
@"using B;
class Class : IGoo, [|Class2|]
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}",
@"using A;
using B;
class Class : IGoo, Class2
{
}
namespace A
{
class Class2
{
}
}
namespace B
{
interface IGoo
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeUnexpanded(TestHost testHost)
{
await TestAsync(
@"[[|Obsolete|]]
class Class
{
}",
@"using System;
[Obsolete]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAttributeExpanded(TestHost testHost)
{
await TestAsync(
@"[[|ObsoleteAttribute|]]
class Class
{
}",
@"using System;
[ObsoleteAttribute]
class Class
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(538018, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538018")]
public async Task TestAfterNew(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Goo()
{
List<int> l;
l = new [|List<int>|]();
}
}",
@"using System.Collections.Generic;
class Class
{
void Goo()
{
List<int> l;
l = new List<int>();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestArgumentsInMethodCall(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test()
{
Console.WriteLine([|DateTime|].Today);
}
}",
@"using System;
class Class
{
void Test()
{
Console.WriteLine(DateTime.Today);
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestCallSiteArgs(TestHost testHost)
{
await TestAsync(
@"class Class
{
void Test([|DateTime|] dt)
{
}
}",
@"using System;
class Class
{
void Test(DateTime dt)
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsePartialClass(TestHost testHost)
{
await TestAsync(
@"namespace A
{
public class Class
{
[|PClass|] c;
}
}
namespace B
{
public partial class PClass
{
}
}",
@"using B;
namespace A
{
public class Class
{
PClass c;
}
}
namespace B
{
public partial class PClass
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestGenericClassInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
[|GenericClass<int>|] c;
}
}",
@"using A.B;
namespace A
{
namespace B
{
class GenericClass<T>
{
}
}
}
namespace C
{
class Class
{
GenericClass<int> c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestExtensionMethods(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
values.[|Where|](i => i > 1);
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
values.Where(i => i > 1);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(541730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541730")]
public async Task TestQueryPatterns(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = [|from v in values
where v > 1
select v + 10|];
}
}",
@"using System.Collections.Generic;
using System.Linq;
class Goo
{
void Bar()
{
var values = new List<int>();
var q = from v in values
where v > 1
select v + 10;
}
}", testHost);
}
// Tests for Insertion Order
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using C;
using D;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace D
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B;
using C;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using C;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using C;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using D;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using D;
using B;
using C;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace C
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B.A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultiplePresortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B.X;
using B.Y;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.A;
using B.X;
using B.Y;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}",
@"using B.Y;
using B.X;
using B.A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestMultipleUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using B.Y;
using B.X;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using B.Y;
using B.X;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace B
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
// System on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings1(TestHost testHost)
{
await TestAsync(
@"using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System;
using System.Collections.Generic;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings3(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A;
using B;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings1(TestHost testHost)
{
await TestAsync(
@"
using C;
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using B;
using System;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings2(TestHost testHost)
{
await TestAsync(
@"using System.Collections.Generic;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using System.Collections.Generic;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings3(TestHost testHost)
{
await TestAsync(
@"using B;
using A;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using B;
using A;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings1(TestHost testHost)
{
await TestAsync(
@"using A.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using A.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleBogusSystemUsings2(TestHost testHost)
{
await TestAsync(
@"using System.System;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System.System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestUsingsWithComments(TestHost testHost)
{
await TestAsync(
@"using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using System;
using System./*...*/.Collections.Generic;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost);
}
// System Not on top cases
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemUnsortedUsings4(TestHost testHost)
{
await TestAsync(
@"
using C;
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using C;
using System;
using B;
using A;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings5(TestHost testHost)
{
await TestAsync(
@"using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
public async Task TestSimpleSystemSortedUsings4(TestHost testHost)
{
await TestAsync(
@"using A;
using B;
class Class
{
void Method()
{
[|Console|].Write(1);
}
}",
@"using A;
using B;
using System;
class Class
{
void Method()
{
Console.Write(1);
}
}",
testHost, options: Option(GenerationOptions.PlaceSystemNamespaceFirst, false));
}
[Fact]
[WorkItem(538136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538136")]
[WorkItem(538763, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538763")]
public async Task TestAddUsingForNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace A
{
class Class
{
[|C|].Test t;
}
}
namespace B
{
namespace C
{
class Test
{
}
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(538220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538220")]
public async Task TestAddUsingForFieldWithFormatting(TestHost testHost)
{
await TestAsync(
@"class C { [|DateTime|] t; }",
@"using System;
class C { DateTime t; }", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(539657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539657")]
public async Task BugFix5688(TestHost testHost)
{
await TestAsync(
@"class Program { static void Main ( string [ ] args ) { [|Console|] . Out . NewLine = ""\r\n\r\n"" ; } } ",
@"using System;
class Program { static void Main ( string [ ] args ) { Console . Out . NewLine = ""\r\n\r\n"" ; } } ", testHost);
}
[Fact]
[WorkItem(539853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539853")]
public async Task BugFix5950()
{
await TestAsync(
@"using System.Console; WriteLine([|Expression|].Constant(123));",
@"using System.Console;
using System.Linq.Expressions;
WriteLine(Expression.Constant(123));",
parseOptions: GetScriptOptions());
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective1(TestHost testHost)
{
await TestAsync(
@"#define goo
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(540339, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540339")]
public async Task TestAddAfterDefineDirective2(TestHost testHost)
{
await TestAsync(
@"#define goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective3(TestHost testHost)
{
await TestAsync(
@"#define goo
/// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
using System;
/// Goo
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterDefineDirective4(TestHost testHost)
{
await TestAsync(
@"#define goo
// Goo
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
// Goo
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExistingBanner(TestHost testHost)
{
await TestAsync(
@"// Banner
// Banner
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"// Banner
// Banner
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias1(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddAfterExternAlias2(TestHost testHost)
{
await TestAsync(
@"#define goo
extern alias Goo;
using System.Collections;
class Program
{
static void Main(string[] args)
{
[|Console|].WriteLine();
}
}",
@"#define goo
extern alias Goo;
using System;
using System.Collections;
class Program
{
static void Main(string[] args)
{
Console.WriteLine();
}
}", testHost);
}
[Fact]
public async Task TestWithReferenceDirective()
{
var resolver = new TestMetadataReferenceResolver(assemblyNames: new Dictionary<string, PortableExecutableReference>()
{
{ "exprs", AssemblyMetadata.CreateFromImage(ResourcesNet451.SystemCore).GetReference() }
});
await TestAsync(
@"#r ""exprs""
[|Expression|]",
@"#r ""exprs""
using System.Linq.Expressions;
Expression",
GetScriptOptions(),
TestOptions.ReleaseDll.WithMetadataReferenceResolver(resolver));
}
[Theory]
[CombinatorialData]
[WorkItem(542643, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542643")]
public async Task TestAssemblyAttribute(TestHost testHost)
{
await TestAsync(
@"[assembly: [|InternalsVisibleTo|](""Project"")]",
@"using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Project"")]", testHost);
}
[Fact]
public async Task TestDoNotAddIntoHiddenRegion()
{
await TestMissingInRegularAndScriptAsync(
@"#line hidden
using System.Collections.Generic;
#line default
class Program
{
void Main()
{
[|DateTime|] d;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddToVisibleRegion(TestHost testHost)
{
await TestAsync(
@"#line default
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
[|DateTime|] d;
#line hidden
}
}
#line default",
@"#line default
using System;
using System.Collections.Generic;
#line hidden
class Program
{
void Main()
{
#line default
DateTime d;
#line hidden
}
}
#line default", testHost);
}
[Fact]
[WorkItem(545248, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545248")]
public async Task TestVenusGeneration1()
{
await TestMissingInRegularAndScriptAsync(
@"class C
{
void Goo()
{
#line 1 ""Default.aspx""
using (new [|StreamReader|]())
{
#line default
#line hidden
}
}");
}
[Fact]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute_ActionCount()
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestActionCountAsync(input, 2);
}
[Theory]
[CombinatorialData]
[WorkItem(545774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545774")]
public async Task TestAttribute(TestHost testHost)
{
var input = @"[ assembly : [|Guid|] ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ";
await TestAsync(
input,
@"using System.Runtime.InteropServices;
[ assembly : Guid ( ""9ed54f84-a89d-4fcd-a854-44251e925f09"" ) ] ", testHost);
}
[Fact]
[WorkItem(546833, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546833")]
public async Task TestNotOnOverloadResolutionError()
{
await TestMissingInRegularAndScriptAsync(
@"namespace ConsoleApplication1
{
class Program
{
void Main()
{
var test = new [|Test|]("""");
}
}
class Test
{
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(17020, "DevDiv_Projects/Roslyn")]
public async Task TestAddUsingForGenericArgument(TestHost testHost)
{
await TestAsync(
@"namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<[|IEnumerable<int>|]>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}",
@"using System.Collections.Generic;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
var inArgument = new InArgument<IEnumerable<int>>(new int[] { 1, 2, 3 });
}
}
public class InArgument<T>
{
public InArgument(T constValue)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(775448, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/775448")]
public async Task ShouldTriggerOnCS0308(TestHost testHost)
{
// CS0308: The non-generic type 'A' cannot be used with type arguments
await TestAsync(
@"using System.Collections;
class Test
{
static void Main(string[] args)
{
[|IEnumerable<int>|] f;
}
}",
@"using System.Collections;
using System.Collections.Generic;
class Test
{
static void Main(string[] args)
{
IEnumerable<int> f;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(838253, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/838253")]
public async Task TestConflictedInaccessibleType(TestHost testHost)
{
await TestAsync(
@"using System.Diagnostics;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
[|Log|] }
}",
@"using System.Diagnostics;
using N;
namespace N
{
public class Log
{
}
}
class C
{
static void Main(string[] args)
{
Log }
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(858085, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858085")]
public async Task TestConflictedAttributeName(TestHost testHost)
{
await TestAsync(
@"[[|Description|]]
class Description
{
}",
@"using System.ComponentModel;
[Description]
class Description
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(872908, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/872908")]
public async Task TestConflictedGenericName(TestHost testHost)
{
await TestAsync(
@"using Task = System.AccessViolationException;
class X
{
[|Task<X> x;|]
}",
@"using System.Threading.Tasks;
using Task = System.AccessViolationException;
class X
{
Task<X> x;
}", testHost);
}
[Fact]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport_ActionCount()
{
await TestActionCountInAllFixesAsync(
@"class C
{
void M(P p)
{
[|Console|]
}
static void Main(string[] args)
{
}
}", count: 1);
}
[Theory]
[CombinatorialData]
[WorkItem(913300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/913300")]
public async Task TestNoDuplicateReport(TestHost testHost)
{
await TestAsync(
@"class C
{
void M(P p)
{
[|Console|] }
static void Main(string[] args)
{
}
}",
@"using System;
class C
{
void M(P p)
{
Console }
static void Main(string[] args)
{
}
}", testHost);
}
[Fact]
[WorkItem(938296, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/938296")]
public async Task TestNullParentInNode()
{
await TestMissingInRegularAndScriptAsync(
@"using System.Collections.Generic;
class MultiDictionary<K, V> : Dictionary<K, HashSet<V>>
{
void M()
{
new HashSet<V>([|Comparer|]);
}
}");
}
[Fact]
[WorkItem(968303, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/968303")]
public async Task TestMalformedUsingSection()
{
await TestMissingInRegularAndScriptAsync(
@"[ class Class
{
[|List<|] }");
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsWithPreExistingExternAlias_FileScopedNamespace(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace ProjectLib;
{
public class Project
{
}
}
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
extern alias P;
using P::ProjectLib;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
extern alias P;
using P::AnotherNS;
using P::ProjectLib;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
Project p = new Project();
var x = new [|AnotherClass()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS
{
public class AnotherClass
{
}
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases
{
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExtern_FileScopedNamespace(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
namespace AnotherNS;
public class AnotherClass
{
}
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference Alias=""P"">lib</ProjectReference>
<Document FilePath=""Program.cs"">
using P::AnotherNS;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
var x = new [|AnotherClass()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"extern alias P;
using P::AnotherNS;
namespace ExternAliases;
class Program
{
static void Main(string[] args)
{
var x = new AnotherClass();
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(875899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/875899")]
public async Task TestAddUsingsNoExternFilterGlobalAlias(TestHost testHost)
{
await TestAsync(
@"class Program
{
static void Main(string[] args)
{
[|INotifyPropertyChanged.PropertyChanged|]
}
}",
@"using System.ComponentModel;
class Program
{
static void Main(string[] args)
{
INotifyPropertyChanged.PropertyChanged
}
}", testHost);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref2()
{
var initialText =
@"/// <summary>
/// This is just like <see cref='[|INotifyPropertyChanged.PropertyChanged|]'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var expectedText =
@"using System.ComponentModel;
/// <summary>
/// This is just like <see cref='INotifyPropertyChanged.PropertyChanged'/>, but this one is mine.
/// </summary>
interface MyNotifyPropertyChanged { }";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref3()
{
var initialText =
@"namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator [|D(MyClass)|]'/>
public class MyClass2
{
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
public class MyClass
{
public static explicit operator N1.D (MyClass f)
{
return default(N1.D);
}
}
/// <seealso cref='MyClass.explicit operator D(MyClass)'/>
public class MyClass2
{
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Fact]
[WorkItem(916368, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/916368")]
public async Task TestAddUsingForCref4()
{
var initialText =
@"namespace N1
{
public class D { }
}
/// <seealso cref='[|Test(D)|]'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var expectedText =
@"using N1;
namespace N1
{
public class D { }
}
/// <seealso cref='Test(D)'/>
public class MyClass
{
public void Test(N1.D i)
{
}
}";
var options = new CSharpParseOptions(documentationMode: DocumentationMode.Diagnose);
await TestAsync(initialText, expectedText, parseOptions: options);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer;
public static class Outer
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType2(TestHost testHost)
{
var initialText =
@"using System;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType3(TestHost testHost)
{
await TestAsync(
@"using System;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{
}",
@"using System;
using static Outer.Inner;
public static class Outer
{
public class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(773614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773614")]
public async Task TestAddStaticType4(TestHost testHost)
{
var initialText =
@"using System;
using Outer;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[[|My|]]
class Test
{}";
var expectedText =
@"using System;
using Outer;
using static Outer.Inner;
public static class Outer
{
public static class Inner
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
}
}
}
[My]
class Test
{}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective1(TestHost testHost)
{
await TestAsync(
@"namespace ns
{
using B = [|Byte|];
}",
@"using System;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective2(TestHost testHost)
{
await TestAsync(
@"using System.Collections;
namespace ns
{
using B = [|Byte|];
}",
@"using System;
using System.Collections;
namespace ns
{
using B = Byte;
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective3(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
namespace ns3
{
namespace ns
{
using B = [|Byte|];
namespace ns4
{
}
}
}
}",
@"using System;
namespace ns2
{
namespace ns3
{
namespace ns
{
using B = Byte;
namespace ns4
{
}
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective4(TestHost testHost)
{
await TestAsync(
@"namespace ns2
{
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = [|Byte|];
}
}
}",
@"namespace ns2
{
using System;
using System.Collections;
namespace ns3
{
namespace ns
{
using System.IO;
using B = Byte;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective5(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System.Collections;
namespace ns
{
using B = [|Byte|];
}
}
}",
@"using System.IO;
namespace ns2
{
using System.Diagnostics;
namespace ns3
{
using System;
using System.Collections;
namespace ns
{
using B = Byte;
}
}
}", testHost);
}
[Fact]
[WorkItem(991463, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991463")]
public async Task TestAddInsideUsingDirective6()
{
await TestMissingInRegularAndScriptAsync(
@"using B = [|Byte|];");
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
void Main(C a)
{
C x = a?[|.B()|];
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class E
{
public static C B(this C c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
void Main(C a)
{
C x = a?.B();
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1064748, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064748")]
public async Task TestAddConditionalAccessExpression2(TestHost testHost)
{
var initialText =
@"<Workspace>
<Project Language=""C#"" AssemblyName=""CSAssembly"" CommonReferences=""true"">
<Document FilePath = ""Program"">
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.[|C()|];
}
public class E
{
}
}
</Document>
<Document FilePath = ""Extensions"">
namespace Extensions
{
public static class D
{
public static C.E C(this C.E c) { return c; }
}
}
</Document>
</Project>
</Workspace> ";
var expectedText =
@"
using Extensions;
public class C
{
public E B { get; private set; }
void Main(C a)
{
int? x = a?.B.C();
}
public class E
{
}
}
";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1089138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1089138")]
public async Task TestAmbiguousUsingName(TestHost testHost)
{
await TestAsync(
@"namespace ClassLibrary1
{
using System;
public class SomeTypeUser
{
[|SomeType|] field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}",
@"namespace ClassLibrary1
{
using System;
using global::SubNamespaceName;
public class SomeTypeUser
{
SomeType field;
}
}
namespace SubNamespaceName
{
using System;
class SomeType
{
}
}
namespace ClassLibrary1.SubNamespaceName
{
using System;
class SomeOtherFile
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
#endif
class Program
{
static void Main(string[] args)
{
var a = [|File|].OpenRead("""");
}
}",
@"#define DEBUG
#if DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using System.IO;
#endif
class Program
{
static void Main(string[] args)
{
var a = File.OpenRead("""");
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective2(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
#if DEBUG
using System.Text;
#endif
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective3(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
using System;
using System.Collections.Generic;
#if DEBUG
using System.Text;
#endif
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingInDirective4(TestHost testHost)
{
await TestAsync(
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
class Program { static void Main ( string [ ] args ) { var a = [|File|] . OpenRead ( """" ) ; } } ",
@"#define DEBUG
#if DEBUG
using System;
#endif
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
class Program { static void Main ( string [ ] args ) { var a = File . OpenRead ( """" ) ; } } ", testHost);
}
[Fact]
public async Task TestInaccessibleExtensionMethod()
{
const string initial = @"
namespace N1
{
public static class C
{
private static bool ExtMethod1(this string arg1)
{
return true;
}
}
}
namespace N2
{
class Program
{
static void Main(string[] args)
{
var x = ""str1"".[|ExtMethod1()|];
}
}
}";
await TestMissingInRegularAndScriptAsync(initial);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForProperty(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.[|Instance|];
}
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
class Program
{
public BindingFlags BindingFlags
{
get
{
return BindingFlags.Instance;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1116011, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1116011")]
public async Task TestAddUsingForField(TestHost testHost)
{
await TestAsync(
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
public B B
{
get
{
return B.[|Instance|];
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}",
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using A;
class Program
{
public B B
{
get
{
return B.Instance;
}
}
}
namespace A
{
public class B
{
public static readonly B Instance;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1893, "https://github.com/dotnet/roslyn/issues/1893")]
public async Task TestNameSimplification(TestHost testHost)
{
// Generated using directive must be simplified from "using A.B;" to "using B;" below.
await TestAsync(
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
class T2
{
void Test()
{
Console.WriteLine();
[|T1|] t1;
}
}
}",
@"namespace A.B
{
class T1
{
}
}
namespace A.C
{
using System;
using A.B;
class T2
{
void Test()
{
Console.WriteLine();
T1 t1;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.[|ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = 0;
b.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(935, "https://github.com/dotnet/roslyn/issues/935")]
public async Task TestAddUsingWithOtherExtensionsInScope2(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
using System.Collections;
using X;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?[|.ExtMethod|](0);
}
}",
@"using System.Linq;
using System.Collections;
using X;
using Y;
namespace X
{
public static class Ext
{
public static void ExtMethod(this int? a)
{
}
}
}
namespace Y
{
public static class Ext
{
public static void ExtMethod(this int? a, int v)
{
}
}
}
public class B
{
static void Main()
{
var b = new int?();
b?.ExtMethod(0);
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope3(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
int i = 0.[|All|]();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
int i = 0.All();
}
namespace X
{
static class E
{
public static int All(this int o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(562, "https://github.com/dotnet/roslyn/issues/562")]
public async Task TestAddUsingWithOtherExtensionsInScope4(TestHost testHost)
{
await TestAsync(
@"using System.Linq;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?[|.All|]();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}",
@"using System.Linq;
using X;
class C
{
static void Main(string[] args)
{
var a = new int?();
int? i = a?.All();
}
}
namespace X
{
static class E
{
public static int? All(this int? o) => 0;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified2(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified3(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified4(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
using Zin32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
using Zin32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified5(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using Microsoft.Win32.SafeHandles;
#if true
using Win32;
#else
using System;
#endif
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(3080, "https://github.com/dotnet/roslyn/issues/3080")]
public async Task TestNestedNamespaceSimplified6(TestHost testHost)
{
await TestAsync(
@"namespace Microsoft.MyApp
{
using System;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
[|SafeRegistryHandle|] h;
}
}
}",
@"namespace Microsoft.MyApp
{
using System;
using Microsoft.Win32.SafeHandles;
#if false
using Win32;
#endif
using Win32;
class Program
{
static void Main(string[] args)
{
SafeRegistryHandle h;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalUppercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var b = new [|B|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using Uppercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var b = new B();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingOrdinalLowercase(TestHost testHost)
{
await TestAsync(
@"namespace A
{
class A
{
static void Main(string[] args)
{
var a = new [|b|]();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}",
@"using lowercase;
namespace A
{
class A
{
static void Main(string[] args)
{
var a = new b();
}
}
}
namespace lowercase
{
class b
{
}
}
namespace Uppercase
{
class B
{
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7443, "https://github.com/dotnet/roslyn/issues/7443")]
public async Task TestWithExistingIncompatibleExtension(TestHost testHost)
{
await TestAsync(
@"using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.[|Any|]
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}",
@"using System.Linq;
using N;
class C
{
int x()
{
System.Collections.Generic.IEnumerable<int> x = null;
return x.Any
}
}
namespace N
{
static class Extensions
{
public static void Any(this string s)
{
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1744, @"https://github.com/dotnet/roslyn/issues/1744")]
public async Task TestIncompleteCatchBlockInLambda(TestHost testHost)
{
await TestAsync(
@"class A
{
System.Action a = () => {
try
{
}
catch ([|Exception|]",
@"using System;
class A
{
System.Action a = () => {
try
{
}
catch (Exception", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|]. }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int>. }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda2(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => { [|List<int>|] }
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => { List<int> }
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda3(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|].
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>.
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1033612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1033612")]
public async Task TestAddInsideLambda4(TestHost testHost)
{
var initialText =
@"using System;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
[|List<int>|]
return a;
};
}";
var expectedText =
@"using System;
using System.Collections.Generic;
static void Main(string[] args)
{
Func<int> f = () => {
var a = 3;
List<int>
return a;
};
}";
await TestAsync(initialText, expectedText, testHost);
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[Theory]
[CombinatorialData]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
public async Task TestIncompleteParenthesizedLambdaExpression(TestHost testHost)
{
await TestAsync(
@"using System;
class Test
{
void Goo()
{
Action a = () => {
[|IBindCtx|] };
string a;
}
}",
@"using System;
using System.Runtime.InteropServices.ComTypes;
class Test
{
void Goo()
{
Action a = () => {
IBindCtx };
string a;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(7461, "https://github.com/dotnet/roslyn/issues/7461")]
public async Task TestExtensionWithIncompatibleInstance(TestHost testHost)
{
await TestAsync(
@"using System.IO;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.[|Write|](new byte[] { 1, 2, 3 });
}
}
}",
@"using System.IO;
using Namespace1;
namespace Namespace1
{
static class StreamExtensions
{
public static void Write(this Stream stream, byte[] bytes)
{
}
}
}
namespace Namespace2
{
class Goo
{
void Bar()
{
Stream stream = null;
stream.Write(new byte[] { 1, 2, 3 });
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(5499, "https://github.com/dotnet/roslyn/issues/5499")]
public async Task TestFormattingForNamespaceUsings(TestHost testHost)
{
await TestAsync(
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class Program
{
void Main()
{
[|Task<int>|]
}
}
}",
@"namespace N
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
void Main()
{
Task<int>
}
}
}", testHost);
}
[Fact]
public async Task TestGenericAmbiguityInSameNamespace()
{
await TestMissingInRegularAndScriptAsync(
@"namespace NS
{
class C<T> where T : [|C|].N
{
public class N
{
}
}
}");
}
[Fact]
public async Task TestNotOnVar1()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class var { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Fact]
public async Task TestNotOnVar2()
{
await TestMissingInRegularAndScriptAsync(
@"namespace N
{
class Bar { }
}
class C
{
void M()
{
[|var|]
}
}
");
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
class C : [|IEnumerable|]<int>
{
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections.Generic;
class C : IEnumerable<int>
{
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfUsing2(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System.Collections;
class C
{
[|DateTime|] d;
}
",
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
using System;
using System.Collections;
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(226826, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=226826")]
public async Task TestAddUsingWithLeadingDocCommentInFrontOfClass1(TestHost testHost)
{
await TestAsync(
@"
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
[|DateTime|] d;
}
",
@"
using System;
/// Copyright 2016 - MyCompany
/// All Rights Reserved
class C
{
DateTime d;
}
", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestPlaceUsingWithUsings_NotWithAliases(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using C = System.Collections;
class Class
{
[|List<int>|] Method()
{
Goo();
}
}
}",
@"
using System;
using System.Collections.Generic;
namespace N
{
using C = System.Collections;
class Class
{
List<int> Method()
{
Goo();
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using System;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(15025, "https://github.com/dotnet/roslyn/issues/15025")]
public async Task TestPreferSystemNamespaceFirst2(TestHost testHost)
{
await TestAsync(
@"
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
[|SomeClass|] c;
}
}",
@"
using Microsoft;
namespace Microsoft
{
public class SomeClass { }
}
namespace System
{
public class SomeClass { }
}
namespace N
{
class Class
{
SomeClass c;
}
}", testHost, index: 1);
}
[Fact]
[WorkItem(18275, "https://github.com/dotnet/roslyn/issues/18275")]
public async Task TestContextualKeyword1()
{
await TestMissingInRegularAndScriptAsync(
@"
namespace N
{
class nameof
{
}
}
class C
{
void M()
{
[|nameof|]
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19218, "https://github.com/dotnet/roslyn/issues/19218")]
public async Task TestChangeCaseWithUsingsInNestedNamespace(TestHost testHost)
{
await TestAsync(
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
[|IVsStatusBar|] b;
}
}
}
",
@"namespace VS
{
interface IVsStatusbar
{
}
}
namespace Outer
{
using System;
using VS;
class C
{
void M()
{
// Note: IVsStatusBar is cased incorrectly.
IVsStatusbar b;
}
}
}
", testHost);
}
[Fact]
[WorkItem(19575, "https://github.com/dotnet/roslyn/issues/19575")]
public async Task TestNoNonGenericsWithGenericCodeParsedAsExpression()
{
var code = @"
class C
{
private void GetEvaluationRuleNames()
{
[|IEnumerable|] < Int32 >
return ImmutableArray.CreateRange();
}
}";
await TestActionCountAsync(code, count: 1);
await TestInRegularAndScriptAsync(
code,
@"
using System.Collections.Generic;
class C
{
private void GetEvaluationRuleNames()
{
IEnumerable < Int32 >
return ImmutableArray.CreateRange();
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome1(TestHost testHost)
{
// System is set to be sorted first, but the actual file shows it at the end.
// Keep things sorted, but respect that 'System' is at the end.
await TestAsync(
@"
using B;
using System;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using A;
using B;
using System;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(19796, "https://github.com/dotnet/roslyn/issues/19796")]
public async Task TestWhenInRome2(TestHost testHost)
{
// System is set to not be sorted first, but the actual file shows it sorted first.
// Keep things sorted, but respect that 'System' is at the beginning.
await TestAsync(
@"
using System;
using B;
class Class
{
void Method()
{
[|Goo|].Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}",
@"
using System;
using A;
using B;
class Class
{
void Method()
{
Goo.Bar();
}
}
namespace A
{
class Goo
{
public static void Bar()
{
}
}
}", testHost);
}
[Fact]
public async Task TestExactMatchNoGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Other|] b;
}
}
", ImmutableArray<string>.Empty);
}
[Fact]
public async Task TestFuzzyMatchGlyph()
{
await TestSmartTagGlyphTagsAsync(
@"namespace VS
{
interface Other
{
}
}
class C
{
void M()
{
[|Otter|] b;
}
}
", WellKnownTagArrays.Namespace);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod1(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|Goo|];
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await Goo;
C Goo { get; set; }
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(29313, "https://github.com/dotnet/roslyn/issues/29313")]
public async Task TestGetAwaiterExtensionMethod2(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
class C
{
async Task M() => await [|GetC|]();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}",
@"
namespace A
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using B;
class C
{
async Task M() => await GetC();
C GetC() => null;
}
}
namespace B
{
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Awaiter GetAwaiter(this C scheduler) => null;
public class Awaiter : INotifyCompletion
{
public object GetResult() => null;
public void OnCompleted(Action continuation) { }
public bool IsCompleted => true;
}
}
}", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(745490, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/745490")]
public async Task TestAddUsingForAwaitableReturningExtensionMethod(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
using System;
using System.Threading.Tasks;
class C
{
C Instance { get; }
async Task M() => await Instance.[|Foo|]();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}",
@"
namespace A
{
using System;
using System.Threading.Tasks;
using B;
class C
{
C Instance { get; }
async Task M() => await Instance.Foo();
}
}
namespace B
{
using System;
using System.Threading.Tasks;
using A;
static class Extensions
{
public static Task Foo(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningIEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}", testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetEnumerator()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in [|Instance|]); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}",
@"
using B;
namespace A
{
class C
{
C Instance { get; };
void M() { foreach (var i in Instance); }
public Enumerator GetAsyncEnumerator(System.Threading.CancellationToken token = default)
{
return new Enumerator();
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetAsyncEnumeratorOnForeach()
{
await TestMissingAsync(
@"
namespace A
{
class C
{
C Instance { get; }
void M() { foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningIAsyncEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable,
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IAsyncEnumerator<int> GetAsyncEnumerator(this C instance) => null;
}
}" + IAsyncEnumerable, testHost);
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumerator(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in Instance); }
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public class Enumerator
{
public int Current { get; }
public Task<bool> MoveNextAsync();
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionInvalidGetAsyncEnumerator()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
async Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
static class Extensions
{
public static bool GetAsyncEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
public async Task TestAddUsingForExtensionGetAsyncEnumeratorReturningPatternEnumeratorWrongAsync(TestHost testHost)
{
await TestAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}",
@"
using System.Threading.Tasks;
using B;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in Instance); }
public Enumerator GetEnumerator()
{
return new Enumerator();
}
public class Enumerator
{
public int Current { get; }
public bool MoveNext();
}
}
}
namespace B
{
using A;
static class Extensions
{
public static Enumerator GetAsyncEnumerator(this C instance) => null;
}
public sealed class Enumerator
{
public async System.Threading.Tasks.Task<bool> MoveNextAsync() => throw null;
public int Current => throw null;
}
}", testHost);
}
[Fact]
public async Task TestMissingForExtensionGetEnumeratorOnAsyncForeach()
{
await TestMissingAsync(
@"
using System.Threading.Tasks;
namespace A
{
class C
{
C Instance { get; }
Task M() { await foreach (var i in [|Instance|]); }
}
}
namespace B
{
using A;
using System.Collections.Generic;
static class Extensions
{
public static IEnumerator<int> GetEnumerator(this C instance) => null;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInInnerNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithStaticUsingInOuterNestedNamespace_WhenNoExistingUsings(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using static System.Math;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenStaticUsingInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using static System.Math;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using static System.Math;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using static System.Math;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenStaticUsingInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using static System.Math;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInInnerNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
namespace M
{
using System.Collections.Generic;
using SAction = System.Action;
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithUsingAliasInOuterNestedNamespace_WhenNoExistingUsing(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System.Collections.Generic;
using SAction = System.Action;
namespace M
{
class C
{
public List<int> F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsingInCompilationUnit_WhenUsingAliasInNamespace(TestHost testHost)
{
await TestAsync(
@"
using System;
namespace N
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
",
@"
using System;
using System.Collections.Generic;
namespace N
{
using SAction = System.Action;
class C
{
public List<int> F;
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInInnerNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using System;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using System;
using System.Collections.Generic;
namespace M
{
using SAction = System.Action;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(30734, "https://github.com/dotnet/roslyn/issues/30734")]
public async Task UsingPlacedWithExistingUsing_WhenUsingAliasInOuterNestedNamespace(TestHost testHost)
{
await TestAsync(
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
class C
{
public [|List<int>|] F;
}
}
}
",
@"
namespace N
{
using SAction = System.Action;
namespace M
{
using System;
using System.Collections.Generic;
class C
{
public [|List<int>|] F;
}
}
}
", testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
public async Task KeepUsingsGrouped1(TestHost testHost)
{
await TestAsync(
@"
using System;
class Program
{
static void Main(string[] args)
{
[|Goo|]
}
}
namespace Microsoft
{
public class Goo
{
}
}",
@"
using System;
using Microsoft;
class Program
{
static void Main(string[] args)
{
Goo
}
}
namespace Microsoft
{
public class Goo
{
}
}", testHost);
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda1()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte");
}
[WorkItem(1239, @"https://github.com/dotnet/roslyn/issues/1239")]
[Fact]
public async Task TestIncompleteLambda2()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class C
{
C()
{
"""".Select(() => {
new [|Byte|]() }",
@"using System;
using System.Linq;
class C
{
C()
{
"""".Select(() => {
new Byte() }");
}
[WorkItem(860648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/860648")]
[WorkItem(902014, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/902014")]
[Fact]
public async Task TestIncompleteSimpleLambdaExpression()
{
await TestInRegularAndScriptAsync(
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => [|IBindCtx|]
string a;
}
}",
@"using System.Linq;
using System.Runtime.InteropServices.ComTypes;
class Program
{
static void Main(string[] args)
{
args[0].Any(x => IBindCtx
string a;
}
}");
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverSameProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""C#"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.cs"">
using System.ComponentModel;
namespace ProjectLib
{
[EditorBrowsable(EditorBrowsableState.Never)]
public class Project
{
}
}
</Document>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableNeverDifferentProject(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Never)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(testHost: testHost));
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOn(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
const string ExpectedDocumentText = @"
using ProjectLib;
class Program
{
static void Main(string[] args)
{
Project p = new [|Project()|];
}
}
";
await TestAsync(InitialWorkspace, ExpectedDocumentText, testHost);
}
[Theory]
[CombinatorialData]
[WorkItem(1266354, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1266354")]
public async Task TestAddUsingsEditorBrowsableAdvancedDifferentProjectOptionOff(TestHost testHost)
{
const string InitialWorkspace = @"
<Workspace>
<Project Language=""Visual Basic"" AssemblyName=""lib"" CommonReferences=""true"">
<Document FilePath=""lib.vb"">
imports System.ComponentModel
namespace ProjectLib
<EditorBrowsable(EditorBrowsableState.Advanced)>
public class Project
end class
end namespace
</Document>
</Project>
<Project Language=""C#"" AssemblyName=""Console"" CommonReferences=""true"">
<ProjectReference>lib</ProjectReference>
<Document FilePath=""Program.cs"">
class Program
{
static void Main(string[] args)
{
[|Project|] p = new Project();
}
}
</Document>
</Project>
</Workspace>";
await TestMissingAsync(InitialWorkspace, new TestParameters(
options: Option(CompletionOptions.HideAdvancedMembers, true),
testHost: testHost));
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/SymbolCompletionProviderTests.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.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion;
using Microsoft.CodeAnalysis.Experiments;
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.CompletionSetSources
{
[UseExportProvider]
public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(SymbolCompletionProvider);
protected override TestComposition GetComposition()
=> base.GetComposition().AddParts(typeof(TestExperimentationService));
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFile(SourceCodeKind sourceCodeKind)
{
await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind)
{
await VerifyItemExistsAsync(@"using System;
$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"using System;
$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashR()
=> await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashLoad()
=> await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirective()
{
await VerifyItemIsAbsentAsync(@"using $$", @"String");
await VerifyItemIsAbsentAsync(@"using $$ = System", @"System");
await VerifyItemExistsAsync(@"using $$", @"System");
await VerifyItemExistsAsync(@"using T = $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegionWithUsing()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegionWithUsing()
{
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineXmlComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenCharLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute1()
{
await VerifyItemExistsAsync(@"[assembly: $$]", @"System");
await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SystemAttributeIsNotAnAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParamAttribute()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodAttribute()
{
var content = @"class CL {
[$$]
void Method() {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodTypeParamAttribute()
{
var content = @"class CL{
void Method<[A$$]T> () {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodParamAttribute()
{
var content = @"class CL{
void Method ([$$]int i) {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_TopLevel()
{
var source = @"namespace $$ { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_Nested()
{
var source = @";
namespace System
{
namespace $$ { }
}";
await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers()
{
var source = @"using System;
namespace $$";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace()
{
var source = @"using System;
namespace $$;";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelWithPeer()
{
var source = @"
namespace A { }
namespace $$";
await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithNoPeers()
{
var source = @"
namespace A
{
namespace $$
}";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B { }
namespace $$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration()
{
var source = @"namespace N$$S";
await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNested()
{
var source = @"
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace $$
namespace C1 { }
}
namespace B.C2 { }
}
namespace A.B.C3 { }";
// Ideally, all the C* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// C1 => A.B.?.C1
// C2 => A.B.B.C2
// C3 => A.A.B.C3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
// Because of the above, B does end up in the completion list
// since A.B.B appears to be a peer of the new declaration
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NoPeers()
{
var source = @"namespace A.$$";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer()
{
var source = @"
namespace A.B { }
namespace A.$$";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace()
{
var source = @"
namespace A.B { }
namespace A.$$;";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B.C { }
namespace B.$$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNested()
{
var source = @"
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem.Runtime { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnKeyword()
{
var source = @"name$$space System { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnNestedKeyword()
{
var source = @"
namespace System
{
name$$space Runtime { }
}";
await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace C.$$
namespace C.D1 { }
}
namespace B.C.D2 { }
}
namespace A.B.C.D3 { }";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
// Ideally, all the D* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// D1 => A.B.C.C.?.D1
// D2 => A.B.B.C.D2
// D3 => A.A.B.C.D3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnderNamespace()
{
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType1()
{
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType2()
{
var content = @"namespace NS {
class CL {}
$$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideProperty()
{
var content = @"class C
{
private string name;
public string Name
{
set
{
name = $$";
await VerifyItemExistsAsync(content, @"value");
await VerifyItemExistsAsync(content, @"C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterDot()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingAlias()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMember()
{
var content = @"class CL {
$$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMemberAccessibility()
{
var content = @"class CL {
public $$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BadStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameter()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameterList()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionTypePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObjectCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StackAllocArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseTypeOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DeclarationStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VariableDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementNoToken()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldDeclaration()
{
var content = @"class CL {
$$ i";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventFieldDeclaration()
{
var content = @"class CL {
event $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclaration()
{
var content = @"class CL {
explicit operator $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclarationNoToken()
{
var content = @"class CL {
explicit $$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PropertyDeclaration()
{
var content = @"class CL {
$$ Prop {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventDeclaration()
{
var content = @"class CL {
event $$ Event {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IndexerDeclaration()
{
var content = @"class CL {
$$ this";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameter()
{
var content = @"class CL {
void Method($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayType()
{
var content = @"class CL {
$$ [";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PointerType()
{
var content = @"class CL {
$$ *";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableType()
{
var content = @"class CL {
$$ ?";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateDeclaration()
{
var content = @"class CL {
delegate $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodDeclaration()
{
var content = @"class CL {
$$ M(";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OperatorDeclaration()
{
var content = @"class CL {
$$ operator";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ElementAccessExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Argument()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseInPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LetClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OrderingExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SelectClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThrowStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System");
}
[WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task YieldReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LockStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EqualsValueClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementInitializersPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementConditionOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementIncrementorsPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DoStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhileStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayRankSpecifierSizesPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrefixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PostfixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenTruePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenFalsePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseInExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseLeftExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseRightExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhereClauseConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseGroupExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseByExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IfStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchLabelCase()
{
var content = @"switch(i) { case $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchPatternLabelCase()
{
var content = @"switch(i) { case $$ when";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionFirstBranch()
{
var content = @"i switch { $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionSecondBranch()
{
var content = @"i switch { 1 => true, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternFirstPosition()
{
var content = @"i is ($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternSecondPosition()
{
var content = @"i is (1, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternFirstPosition()
{
var content = @"i is { P: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternSecondPosition()
{
var content = @"i is { P1: 1, P2: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InitializerExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseList()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseAnotherWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause1()
{
await VerifyItemExistsAsync(@"class CL<T> where $$", @"T");
await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T");
await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause2()
{
await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause3()
{
await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1");
await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseListWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedName()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedNamespace()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedType()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstructorInitializer()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Checked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Unchecked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Locals()
=> await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameters()
=> await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AnonymousMethodDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommonTypesInNewExpressionContext()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionForUnboundTypes()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInTypeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInDefault()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInSizeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInGenericParameterList()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterNumericLiteral()
{
// NOTE: the Completion command handler will suppress this case if the user types '.',
// but we still need to show members if the user specifically invokes statement completion here.
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterParenthesizedNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedNumericLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterArithmeticExpression()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals");
[WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceTypesAvailableInUsingAlias()
=> await VerifyItemExistsAsync(@"using S = System.$$", "String");
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember1()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember2()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
this.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember3()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
base.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember1()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember2()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
B.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember3()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
A.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedInstanceAndStaticMembers()
{
var markup = @"
class A
{
private static void HiddenStatic() { }
protected static void GooStatic() { }
private void HiddenInstance() { }
protected void GooInstance() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "HiddenStatic");
await VerifyItemExistsAsync(markup, "GooStatic");
await VerifyItemIsAbsentAsync(markup, "HiddenInstance");
await VerifyItemExistsAsync(markup, "GooInstance");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer1()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer2()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; i < 10; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersInClass()
{
var markup = @"
class C<T, R>
{
$$
}
";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(ref $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(out $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(in $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(ref String parameter)
{
M(ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(out String parameter)
{
M(out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(in String parameter)
{
M(in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefExpression_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref var x = ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref readonly $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType1()
{
var markup = @"
class Q
{
$$
class R
{
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType2()
{
var markup = @"
class Q
{
class R
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType3()
{
var markup = @"
class Q
{
class R
{
}
$$
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Regular()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
// Top-level statements are not allowed to follow classes, but we still offer it in completion for a few
// reasons:
//
// 1. The code is simpler
// 2. It's a relatively rare coding practice to define types outside of namespaces
// 3. It allows the compiler to produce a better error message when users type things in the wrong order
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Script()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType5()
{
var markup = @"
class Q
{
class R
{
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType6()
{
var markup = @"
class Q
{
class R
{
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenTypeAndLocal()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public void goo() {
int i = 5;
i.$$
List<string> ml = new List<string>();
}
}";
await VerifyItemExistsAsync(markup, "CompareTo");
}
[WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
AwaitTest test = new AwaitTest();
test.Test1().Wait();
}
}
class AwaitTest
{
List<string> stringList = new List<string>();
public async Task<bool> Test1()
{
stringList.$$
await Test2();
return true;
}
public async Task<bool> Test2()
{
return true;
}
}";
await VerifyItemExistsAsync(markup, "Add");
}
[WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterNewInScript()
{
var markup = @"
using System;
new $$";
await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodsInScript()
{
var markup = @"
using System.Linq;
var a = new int[] { 1, 2 };
a.$$";
await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionsInForLoopInitializer()
{
var markup = @"
public class C
{
public void M()
{
int count = 0;
for ($$
";
await VerifyItemExistsAsync(markup, "count");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression1()
{
var markup = @"
public class C
{
public void M()
{
System.Func<int, int> f = arg => { arg = 2; return arg; }.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "ToString");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression2()
{
var markup = @"
public class C
{
public void M()
{
((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$
}
}
";
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemExistsAsync(markup, "Invoke");
}
[WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InMultiLineCommentAtEndOfFile()
{
var markup = @"
using System;
/*$$";
await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersAtEndOfFile()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Outer<T>
{
class Inner<U>
{
static void F(T t, U u)
{
return;
}
public static void F(T t)
{
Outer<$$";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForCase()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "case 0:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "default:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchPresentForDefault()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
default:
goto $$";
await VerifyItemExistsAsync(markup, "default");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto1()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto $$";
await VerifyItemExistsAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto2()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto Goo $$";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeName()
{
var markup = @"
using System;
[$$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifier()
{
var markup = @"
using System;
[assembly:$$
";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeList()
{
var markup = @"
using System;
[CLSCompliant, $$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameBeforeClass()
{
var markup = @"
using System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifierBeforeClass()
{
var markup = @"
using System;
[assembly:$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeArgumentList()
{
var markup = @"
using System;
[CLSCompliant($$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInsideClass()
{
var markup = @"
using System;
class C { $$ }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName1()
{
var markup = @"
using Alias = System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName2()
{
var markup = @"
using Alias = Goo;
namespace Goo { }
[$$
class C { }";
await VerifyItemIsAbsentAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName3()
{
var markup = @"
using Alias = Goo;
namespace Goo { class A : System.Attribute { } }
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace()
{
var markup = @"
namespace Test
{
class MyAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace2()
{
var markup = @"
namespace Test
{
namespace Two
{
class MyAttribute : System.Attribute { }
[Test.Two.$$
class Program { }
}
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task KeywordsUsedAsLocals()
{
var markup = @"
class C
{
void M()
{
var error = 0;
var method = 0;
var @int = 0;
Console.Write($$
}
}";
// preprocessor keyword
await VerifyItemExistsAsync(markup, "error");
await VerifyItemIsAbsentAsync(markup, "@error");
// contextual keyword
await VerifyItemExistsAsync(markup, "method");
await VerifyItemIsAbsentAsync(markup, "@method");
// full keyword
await VerifyItemExistsAsync(markup, "@int");
await VerifyItemIsAbsentAsync(markup, "int");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords1()
{
var markup = @"
class C
{
void M()
{
var from = new[]{1,2,3};
var r = from x in $$
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords2()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where $$ == @where.Length
select @from;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords3()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where @from == @where.Length
select $$;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAlias()
{
var markup = @"
class MyAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword()
{
var markup = @"
class namespaceAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute1()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute2()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace2");
await VerifyItemExistsAsync(markup, "Namespace3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute3()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.$$]";
await VerifyItemExistsAsync(markup, "Namespace4");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute4()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.Namespace4.$$]";
await VerifyItemExistsAsync(markup, "Custom");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias()
{
var markup = @"
using Namespace1Alias = Namespace1;
using Namespace2Alias = Namespace1.Namespace2;
using Namespace3Alias = Namespace1.Namespace3;
using Namespace4Alias = Namespace1.Namespace3.Namespace4;
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1Alias");
await VerifyItemIsAbsentAsync(markup, "Namespace2Alias");
await VerifyItemExistsAsync(markup, "Namespace3Alias");
await VerifyItemExistsAsync(markup, "Namespace4Alias");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithoutNestedAttribute()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } }
}
[$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace1");
}
[WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariableInQuerySelect()
{
var markup = @"
using System.Linq;
class P
{
void M()
{
var src = new string[] { ""Goo"", ""Bar"" };
var q = from x in src
select x.$$";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsPatternExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ 1";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchPatternCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$ when";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchGotoCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case MAX_SIZE:
break;
case GOO:
goto case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInEnumMember()
{
var markup = @"
class C
{
public const int GOO = 0;
enum E
{
A = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute1()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage($$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute2()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(GOO, $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute3()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(validOn: $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute4()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(AllowMultiple = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInParameterDefaultValue()
{
var markup = @"
class C
{
public const int GOO = 0;
void M(int x = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstField()
{
var markup = @"
class C
{
public const int GOO = 0;
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstLocal()
{
var markup = @"
class C
{
public const int GOO = 0;
void M()
{
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1Overload()
{
var markup = @"
class C
{
void M(int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ย 1ย {FeaturesResources.overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2Overloads()
{
var markup = @"
class C
{
void M(int i) { }
void M(out int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ย 2ย {FeaturesResources.overloads_})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1GenericOverload()
{
var markup = @"
class C
{
void M<T>(T i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ย 1ย {FeaturesResources.generic_overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2GenericOverloads()
{
var markup = @"
class C
{
void M<T>(int i) { }
void M<T>(out int i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ย 2ย {FeaturesResources.generic_overloads})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionNamedGenericType()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionParameter()
{
var markup = @"
class C<T>
{
void M(T goo)
{
$$";
await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionGenericTypeParameter()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionAnonymousType()
{
var markup = @"
class C
{
void M()
{
var a = new { };
$$
";
var expectedDescription =
$@"({FeaturesResources.local_variable}) 'a a
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}";
await VerifyItemExistsAsync(markup, "a", expectedDescription);
}
[WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterNewInAnonymousType()
{
var markup = @"
class Program {
string field = 0;
static void Main() {
var an = new { new $$ };
}
}
";
await VerifyItemExistsAsync(markup, "Program");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticMethod()
{
var markup = @"
class C
{
int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
int x = 0;
static int y = $$
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticMethod()
{
var markup = @"
class C
{
static int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
static int x = 0;
static int y = $$
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemIsAbsentAsync(markup, "i");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
static int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OnlyEnumMembersInEnumMemberAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
x.$$
}
}
";
await VerifyItemExistsAsync(markup, "a");
await VerifyItemExistsAsync(markup, "b");
await VerifyItemExistsAsync(markup, "c");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoEnumMembersInEnumLocalAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
var y = x.a;
y.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "a");
await VerifyItemIsAbsentAsync(markup, "b");
await VerifyItemIsAbsentAsync(markup, "c");
await VerifyItemExistsAsync(markup, "Equals");
}
[WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaParameterDot()
{
var markup = @"
using System;
using System.Linq;
class A
{
public event Func<String, String> E;
}
class Program
{
static void Main(string[] args)
{
new A().E += ss => ss.$$
}
}
";
await VerifyItemExistsAsync(markup, "Substring");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAtRoot_Interactive()
{
await VerifyItemIsAbsentAsync(
@"$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterClass_Interactive()
{
await VerifyItemIsAbsentAsync(
@"class C { }
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalStatement_Interactive()
{
await VerifyItemIsAbsentAsync(
@"System.Console.WriteLine();
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyItemIsAbsentAsync(
@"int i = 0;
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInUsingAlias()
{
await VerifyItemIsAbsentAsync(
@"using Goo = $$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInEmptyStatement()
{
await VerifyItemIsAbsentAsync(AddInsideMethod(
@"$$"),
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideSetter()
{
await VerifyItemExistsAsync(
@"class C {
int Goo {
set {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideAdder()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
add {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideRemover()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
remove {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterDot()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
this.$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterArrow()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a->$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterColonColon()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a::$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInGetter()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
get {
$$",
"value");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterNullableTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkAndPartialIdentifierInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskAndPartialIdentifierInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* f$$",
"goo");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterEventFieldDeclaredInSameType()
{
await VerifyItemExistsAsync(
@"class C {
public event System.EventHandler E;
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterFullEventDeclaredInSameType()
{
await VerifyItemIsAbsentAsync(
@"class C {
public event System.EventHandler E { add { } remove { } }
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterEventDeclaredInDifferentType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
System.Console.CancelKeyPress.$$",
"Invoke");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInObjectInitializerMemberContext()
{
await VerifyItemIsAbsentAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$",
"x");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task AfterPointerMemberAccess()
{
await VerifyItemExistsAsync(@"
struct MyStruct
{
public int MyField;
}
class Program
{
static unsafe void Main(string[] args)
{
MyStruct s = new MyStruct();
MyStruct* ptr = &s;
ptr->$$
}}",
"MyField");
}
// After @ both X and XAttribute are legal. We think this is an edge case in the language and
// are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed.
[WorkItem(11931, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task VerbatimAttributes()
{
var code = @"
using System;
public class X : Attribute
{ }
public class XAttribute : Attribute
{ }
[@X$$]
class Class3 { }
";
await VerifyItemExistsAsync(code, "X");
await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute"));
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; $$
}
}
", "Console");
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for ($$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclaration()
{
// "int goo = goo = 1" is a legal declaration
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclarator()
{
// "int bar = bar = 1" is legal in a declarator
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$, int baz = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclaration()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
$$
int goo = 0;
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclarator()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
int goo = $$, bar = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAfterDeclarator()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAsOutArgumentInInitializerExpression()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = Bar(out $$
}
int Bar(out int x)
{
x = 3;
return 5;
}
}", "goo");
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverriddenSymbolsFilteredFromCompletionList()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
public class B
{
public virtual void Goo(int original)
{
}
}
public class D : B
{
public override void Goo(int derived)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
C c = new C();
c.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Goo()
{
}
}
public class D : B
{
public void Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
$$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")]
[WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")]
[WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
public int Bar {
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads1()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads2()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateNever()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAlways()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
public class Goo : Bar
{
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Bar
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAlways()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Always()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Never()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 0,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestColorColor1()
{
var markup = @"
class A
{
static void Goo() { }
void Bar() { }
static void Main()
{
A A = new A();
A.$$
}
}";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType1()
{
var markup = @"
using System;
class C
{
public static void Main()
{
$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType2()
{
var markup = @"
using System;
class C
{
public static void Main()
{
C$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "IndexProp",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
[WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestDeclarationAmbiguity()
{
var markup = @"
using System;
class Program
{
void Main()
{
Environment.$$
var v;
}
}";
await VerifyItemExistsAsync(markup, "CommandLine");
}
[WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldDeclarationAmbiguity()
{
var markup = @"
using System;
Environment.$$
var v;
}";
await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestCursorOnClassCloseBrace()
{
var markup = @"
using System;
class Outer
{
class Inner { }
$$}";
await VerifyItemExistsAsync(markup, "Inner");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync1()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async $$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
public async T$$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterAsyncInMethodBody()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void goo()
{
var x = async $$
}
}";
await VerifyItemIsAbsentAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable1()
{
var markup = @"
class Program
{
void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable2()
{
var markup = @"
class Program
{
async void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable1()
{
var markup = @"
using System.Threading;
using System.Threading.Tasks;
class Program
{
async Task goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int> goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpression()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = await request.$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
// Nothing should be found: no awaiter for request.
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Task<Request>();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
$$
}
}";
await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()");
}
[WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersOnDottingIntoUnboundType()
{
var markup = @"
class Program
{
RegistryKey goo;
static void Main(string[] args)
{
goo.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeArgumentsInConstraintAfterBaselist()
{
var markup = @"
public class Goo<T> : System.Object where $$
{
}";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoDestructor()
{
var markup = @"
class C
{
~C()
{
$$
";
await VerifyItemIsAbsentAsync(markup, "Finalize");
}
[WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodOnCovariantInterface()
{
var markup = @"
class Schema<T> { }
interface ISet<out T> { }
static class SetMethods
{
public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { }
}
class Context
{
public ISet<T> Set<T>() { return null; }
}
class CustomSchema : Schema<int> { }
class Program
{
static void Main(string[] args)
{
var set = new Context().Set<CustomSchema>();
set.$$
";
await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachInsideParentheses()
{
var markup = @"
using System;
class C
{
void M()
{
foreach($$)
";
await VerifyItemExistsAsync(markup, "String");
}
[WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldInitializerInP2P()
{
var markup = @"
class Class
{
int i = Consts.$$;
}";
var referencedCode = @"
public static class Consts
{
public const int C = 1;
}";
await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false);
}
[WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowWithEqualsSign()
{
var markup = @"
class c { public int value {set; get; }}
class d
{
void goo()
{
c goo = new c { value$$=
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterThisDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
this.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
base.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInScriptContext()
=> await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script);
[WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoNestedTypeWhenDisplayingInstance()
{
var markup = @"
class C
{
class D
{
}
void M2()
{
new C().$$
}
}";
await VerifyItemIsAbsentAsync(markup, "D");
}
[WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchVariableInExceptionFilter()
{
var markup = @"
class C
{
void M()
{
try
{
}
catch (System.Exception myExn) when ($$";
await VerifyItemExistsAsync(markup, "myExn");
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterExternAlias()
{
var markup = @"
class C
{
void goo()
{
global::$$
}
}";
await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true);
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExternAliasSuggested()
{
var markup = @"
extern alias Bar;
class C
{
void goo()
{
$$
}
}";
await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false);
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ClassDestructor()
{
var markup = @"
class C
{
class N
{
~$$
}
}";
await VerifyItemExistsAsync(markup, "N");
await VerifyItemIsAbsentAsync(markup, "C");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task TildeOutsideClass()
{
var markup = @"
class C
{
class N
{
}
}
~$$";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "N");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StructDestructor()
{
var markup = @"
struct C
{
~$$
}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData("record")]
[InlineData("record class")]
public async Task RecordDestructor(string record)
{
var markup = $@"
{record} C
{{
~$$
}}";
await VerifyItemExistsAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RecordStructDestructor()
{
var markup = $@"
record struct C
{{
~$$
}}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
int x;
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnionOfItemsFromBothContexts()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
class G
{
public void DoGStuff() {}
}
#endif
void goo()
{
new G().$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
int xyz;
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
#if PROJ1
int xyz;
#endif
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
LABEL: int xyz;
goto $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.label}) LABEL";
await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] { 1, 2, 3 } select $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.range_variable}) ? y";
await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription);
}
[WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void Shared()
{
var x = GetThing();
x.$$
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
public int x;
#endif
#if TWO
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({ FeaturesResources.field }) int C.x";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if TWO
public int x;
#endif
#if ONE
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = "int C.x { get; set; }";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessWalkUp()
{
var markup = @"
public class B
{
public A BA;
public B BB;
}
class A
{
public A AA;
public A AB;
public int? x;
public void goo()
{
A a = null;
var q = a?.$$AB.BA.AB.BA;
}
}";
await VerifyItemExistsAsync(markup, "AA");
await VerifyItemExistsAsync(markup, "AB");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
A a = null;
var q = a?.s?.$$;
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped2()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
var q = s?.$$i?.ToString();
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt?.$$
}
}
";
await VerifyItemExistsAsync(markup, "Day");
await VerifyItemIsAbsentAsync(markup, "Value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableIsNotUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt.$$
}
}
";
await VerifyItemExistsAsync(markup, "Value");
await VerifyItemIsAbsentAsync(markup, "Day");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterConditionalIndexing()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S[] s;
public void goo()
{
A a = null;
var q = a?.s?[$$;
}
}";
await VerifyItemExistsAsync(markup, "System");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses1()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.$$b?.c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses2()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.$$c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "c");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses3()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.c?.$$d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "d");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnSelf()
{
var markup = @"using System;
[My]
class X
{
[My$$]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnOuterType()
{
var markup = @"using System;
[My]
class Y
{
}
[$$]
class X
{
[My]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType()
{
var markup = @"abstract class Test
{
private int _field;
public sealed class InnerTest : Test
{
public void SomeTest()
{
$$
}
}
}";
await VerifyItemExistsAsync(markup, "_field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType2()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
$$ // M recommended and accessible
}
class NN
{
void Test2()
{
// M inaccessible and not recommended
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType3()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN
{
void Test2()
{
$$ // M inaccessible and not recommended
}
}
}
}";
await VerifyItemIsAbsentAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType4()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN : N
{
void Test2()
{
$$ // M accessible and recommended.
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType5()
{
var markup = @"
class D
{
public void Q() { }
}
class C<T> : D
{
class N
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Q");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType6()
{
var markup = @"
class Base<T>
{
public int X;
}
class Derived : Base<int>
{
class Nested
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "X");
}
[WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoTypeParametersDefinedInCrefs()
{
var markup = @"using System;
/// <see cref=""Program{T$$}""/>
class Program<T> { }";
await VerifyItemIsAbsentAsync(markup, "T");
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList1()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList2()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<string,$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionInAliasedType()
{
var markup = @"
using IAlias = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C
{
I$$
}
";
await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinNameOf()
{
var markup = @"
class C
{
void goo()
{
var x = nameof($$)
}
}
";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y1");
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y2");
}
[WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteDeclarationExpressionType()
{
var markup = @"
using System;
class C
{
void goo()
{
var x = Console.$$
var y = 3;
}
}
";
await VerifyItemExistsAsync(markup, "WriteLine");
}
[WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticAndInstanceInNameOf()
{
var markup = @"
using System;
class C
{
class D
{
public int x;
public static int y;
}
void goo()
{
var z = nameof(C.D.$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
await VerifyItemExistsAsync(markup, "y");
}
[WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForLocals()
{
var markup = @"class C
{
void M()
{
var x = nameof(T.z.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes2()
{
var markup = @"class C
{
void M()
{
var x = nameof(U.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes3()
{
var markup = @"class C
{
void M()
{
var x = nameof(N.$$)
}
}
namespace N
{
public class U
{
public int nope;
}
} ";
await VerifyItemExistsAsync(markup, "U");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes4()
{
var markup = @"
using z = System;
class C
{
void M()
{
var x = nameof(z.$$)
}
}
";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings1()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$
";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings2()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$}"";
}
}";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings3()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings4()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings5()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings6()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBeforeFirstStringHole()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBetweenStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task CompletionAfterTypeOfGetType()
{
await VerifyItemExistsAsync(AddInsideMethod(
"typeof(int).GetType().$$"), "GUID");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives1()
{
var markup = @"
using $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives2()
{
var markup = @"
using N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives3()
{
var markup = @"
using G = $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives4()
{
var markup = @"
using G = N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives5()
{
var markup = @"
using static $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives6()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates1()
{
var markup = @"
using static $$
class A { }
delegate void B();
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates2()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
delegate void D();
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces1()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
interface I { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces2()
{
var markup = @"
using static $$
class A { }
interface I { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods1()
{
var markup = @"
using static A;
using static B;
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods2()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods3()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods4()
{
var markup = @"
using static N.A;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods5()
{
var markup = @"
using static N.A;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods6()
{
var markup = @"
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods7()
{
var markup = @"
using N;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$;
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinSameClassOfferedForCompletion()
{
var markup = @"
public static class Test
{
static void TestB()
{
$$
}
static void TestA(this string s) { }
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinParentClassOfferedForCompletion()
{
var markup = @"
public static class Parent
{
static void TestA(this string s) { }
static void TestC(string s) { }
public static class Test
{
static void TestB()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when $$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when $$
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause1()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case 1 when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause2()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case int i when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionContextCompletionWithinCast()
{
var markup = @"
class Program
{
void M()
{
for (int i = 0; i < 5; i++)
{
var x = ($$)
var y = 1;
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInPropertyInitializer()
{
var markup = @"
class A {
int abc;
int B { get; } = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInPropertyInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
Action abc;
event Action B = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldInitializer()
{
var markup = @"
int aaa = 1;
int bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldLikeEventInitializer()
{
var markup = @"
Action aaa = null;
event Action bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes1()
{
var markup = @"
using A = System
class C
{
A?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes2()
{
var markup = @"
class C
{
System?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes3()
{
var markup = @"
class C
{
System.Console?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInIncompletePropertyDeclaration()
{
var markup = @"
class Class1
{
public string Property1 { get; set; }
}
class Class2
{
public string Property { get { return this.Source.$$
public Class1 Source { get; set; }
}";
await VerifyItemExistsAsync(markup, "Property1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionInShebangComments()
{
await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script);
await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompoundNameTargetTypePreselection()
{
var markup = @"
class Class1
{
void goo()
{
int x = 3;
string y = x.$$
}
}";
await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer1()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer2()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { 1, $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer1()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer2()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = 1, Y = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElements()
{
var markup = @"
class C
{
void goo()
{
var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9);
t.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
await VerifyItemExistsAsync(markup, "Alice");
await VerifyItemExistsAsync(markup, "Bob");
await VerifyItemExistsAsync(markup, "CompareTo");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "GetType");
await VerifyItemExistsAsync(markup, "Item2");
await VerifyItemExistsAsync(markup, "ITEM3");
for (var i = 4; i <= 8; i++)
{
await VerifyItemExistsAsync(markup, "Item" + i);
}
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemIsAbsentAsync(markup, "Item1");
await VerifyItemIsAbsentAsync(markup, "Item9");
await VerifyItemIsAbsentAsync(markup, "Rest");
await VerifyItemIsAbsentAsync(markup, "Item3");
}
[WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElementsCompletionOffMethodGroup()
{
var markup = @"
class C
{
void goo()
{
new object().ToString.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
// should not crash
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task NoCompletionInLocalFuncGenericParamList()
{
var markup = @"
class C
{
void M()
{
int Local<$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task CompletionForAwaitWithoutAsync()
{
var markup = @"
class C
{
void M()
{
await Local<$$";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel1()
{
await VerifyItemExistsAsync(@"
class C
{
($$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel2()
{
await VerifyItemExistsAsync(@"
class C
{
($$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel3()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel4()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInForeach()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
foreach ((C, $$
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInParameterList()
{
await VerifyItemExistsAsync(@"
class C
{
void M((C, $$)
{
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInNameOf()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
var x = nameof((C, $$
}
}", "C");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
void Local() { }
$$
}
}", "Local", "void Local()");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription2()
{
await VerifyItemExistsAsync(@"
using System;
class C
{
class var { }
void M()
{
Action<int> Local(string x, ref var @class, params Func<int, string> f)
{
return () => 0;
}
$$
}
}", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)");
}
[WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterDot()
{
var markup =
@"namespace ConsoleApplication253
{
class Program
{
static void Main(string[] args)
{
M(E.$$)
}
static void M(E e) { }
}
enum E
{
A,
B,
}
}
";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup1()
{
var markup =
@"namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Main.$$
}
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup2()
{
var markup =
@"class C {
void M<T>() {M<C>.$$ }
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup3()
{
var markup =
@"class C {
void M() {M.$$}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember()
{
var markup =
@"public static class Extensions { public static T Get<T>(this object o) => $$}
";
await VerifyItemExistsAsync(markup, "o");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task EnumConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Enum");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Delegate");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task MulticastDelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "MulticastDelegate");
}
private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString)
{
var template = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ThenIncludeIntellisenseBug
{
class Program
{
static void Main(string[] args)
{
var registrations = new List<Registration>().AsQueryable();
var reg = registrations.Include(r => r.Activities).ThenInclude([1]);
}
}
internal class Registration
{
public ICollection<Activity> Activities { get; set; }
}
public class Activity
{
public Task Task { get; set; }
}
public class Task
{
public string Name { get; set; }
}
public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity>
{
}
public static class EntityFrameworkQuerybleExtensions
{
public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>(
this IQueryable<TEntity> source,
Expression<Func<TEntity, TProperty>> navigationPropertyPath)
where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
[2]
}
}";
return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenInclude()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoExpression()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgument()
{
var markup = CreateThenIncludeTestCode("0, b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentNoOverlap()
{
var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath,
Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemIsAbsentAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeGenericAndNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<Registration, Activity> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<ICollection<Activity>, Activity> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Activity>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaWithOverloads()
{
var markup = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ClassLibrary1
{
class SomeItem
{
public string A;
public int B;
}
class SomeCollection<T> : List<T>
{
public virtual SomeCollection<T> Include(string path) => null;
}
static class Extensions
{
public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path)
=> null;
public static IList Include(this IList source, string path) => null;
public static IList<T> Include<T>(this IList<T> source, string path) => null;
}
class Program
{
void M(SomeCollection<SomeItem> c)
{
var a = from m in c.Include(t => t.$$);
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads2()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(string s) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads3()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M((int p) => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads4()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemExistsAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParameters()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new List<Product>(), arg => arg.$$);
}
static void Create<T>(List<T> list, Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1, Product2>(), arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads2()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1,Product2>(),arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }
class Product3 { public void MyProperty3() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
await VerifyItemExistsAsync(markup, "MyProperty3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClass()
{
var markup = @"
using System;
class Program<T>
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemIsAbsentAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType()
{
var markup = @"
using System;
class Program<T> where T : Product
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod()
{
var markup = @"
using System;
class Program
{
static void M()
{
Create(arg => arg.$$);
}
static void Create<T>(Action<T> expression) where T : Product { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x = 7, Action<string> y = null) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x, int z, Action<string> y) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive()
{
var markup = @"
using System;
static class CExtensions
{
public static void X(this C x, Action<string> y) { }
}
class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive()
{
var markup = @"
using System;
public static void X(this C x, Action<string> y) { }
public class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithNonFunctionsAsArguments()
{
var markup = @"
using System;
class c
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> configure)
{
var builder = new Builder();
configure(builder);
}
}
class Builder
{
public int Something { get; set; }
}";
await VerifyItemExistsAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAsArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1(Uri u);
public delegate void Delegate2(Guid g);
public void M(Delegate1 d) { }
public void M(Delegate2 d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Uri
await VerifyItemExistsAsync(markup, "AbsoluteUri");
await VerifyItemExistsAsync(markup, "Fragment");
await VerifyItemExistsAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1<T1,T2>(T2 t2, T1 t1);
public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1);
public void M(Delegate1<Uri,Guid> d) { }
public void M(Delegate2<Uri,Guid> d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Should not appear for Uri
await VerifyItemIsAbsentAsync(markup, "AbsoluteUri");
await VerifyItemIsAbsentAsync(markup, "Fragment");
await VerifyItemIsAbsentAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsBeforeParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "AnotherSomething");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "Something");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsInParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(b0 => { }, b1 => {}, b2 => { b2.$$ });
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "AnotherSomething");
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilterWithExperimentEnabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestNoTargetTypeFilterWithExperimentDisabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, false);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotOnObjectMembers()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "GetHashCode",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotNamedTypes()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(C c)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "c",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter });
await VerifyItemExistsAsync(
markup, "C",
matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch()
{
var markup = @"
public static class Ext
{
public static void DoSomething<T>(this T thing, string s) where T : class, I
{
}
}
public interface I
{
}
public class C
{
public void M(string s)
{
this.$$
}
}";
await VerifyItemExistsAsync(markup, "M");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>");
}
[WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionInStaticMethod()
{
await VerifyItemExistsAsync(@"
class C
{
static void M()
{
void Local() { }
$$
}
}", "Local");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")]
public async Task NoItemWithEmptyDisplayName()
{
var markup = @"
class C
{
static void M()
{
int$$
}
}
";
await VerifyItemIsAbsentAsync(
markup, "",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter });
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
F$$
}
private void Foo(int i)
{
}
private void Foo(int i, int c)
{
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(){commitChar}
}}
private void Foo(int i)
{{
}}
private void Foo(int i, int c)
{{
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithSemicolonInNestedMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
Foo(F$$);
}
private int Foo(int i)
{
return 1;
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(Foo(){commitChar});
}}
private int Foo(int i)
{{
return 1;
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar)
{
var markup = @"
using System;
class Program
{
private void Bar()
{
Bar2(F$$);
}
private void Foo()
{
}
void Bar2(Action t) { }
}";
var expected = $@"
using System;
class Program
{{
private void Bar()
{{
Bar2(Foo{commitChar});
}}
private void Foo()
{{
}}
void Bar2(Action t) {{ }}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = new P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = new Program(){commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = Program{commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar)
{
var markup = @"
using String2 = System.String;
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = new S$$
}
}
}";
var expected = $@"
using String2 = System.String;
namespace Bar1
{{
class Program
{{
private static void Bar()
{{
var o = new String2(){commitChar}
}}
}}
}}";
await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionWithSemicolonUnderNameofContext()
{
var markup = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(B$$)
}
}
}";
var expected = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(Bar;)
}
}
}";
await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';');
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatchWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPropertyPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
public RankedMusicians R;
void M(C m)
{
if (m is { R: RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ChildClassAfterPatternMatch()
{
var markup =
@"namespace N
{
public class D { public class E { } }
class C
{
void M(object m)
{
if (m is D.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "E");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpression()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpressionWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ย 1ย {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
[System.Obsolete]
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ย 1ย {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IgnoreCustomObsoleteAttribute()
{
var markup =
@"
public class ObsoleteAttribute: System.Attribute
{
}
public class C
{
[Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ย 1ย {FeaturesResources.overload})");
}
[InlineData("int", "")]
[InlineData("int[]", "int a")]
[Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList)
{
// Check the description displayed is based on symbol matches targeted type
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
$@"public class C
{{
bool Bar(int a, int b) => false;
int Bar() => 0;
int[] Bar(int a) => null;
bool N({targetType} x) => true;
void M(C c)
{{
N(c.$$);
}}
}}";
await VerifyItemExistsAsync(
markup, "Bar",
expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesNotSuggestedInDeclarationDeconstruction()
{
await VerifyItemIsAbsentAsync(@"
class C
{
int M()
{
var (x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
(x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
int y;
(var x, $$) = (0, 0);
}
}", "y");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")]
public async Task TestTypeParameterConstraintedToInterfaceWithStatics()
{
var source = @"
interface I1
{
static void M0();
static abstract void M1();
abstract static int P1 { get; set; }
abstract static event System.Action E1;
}
interface I2
{
static abstract void M2();
}
class Test
{
void M<T>(T x) where T : I1, I2
{
T.$$
}
}
";
await VerifyItemIsAbsentAsync(source, "M0");
await VerifyItemExistsAsync(source, "M1");
await VerifyItemExistsAsync(source, "M2");
await VerifyItemExistsAsync(source, "P1");
await VerifyItemExistsAsync(source, "E1");
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.AsyncCompletion;
using Microsoft.CodeAnalysis.Experiments;
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.CompletionSetSources
{
[UseExportProvider]
public partial class SymbolCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType()
=> typeof(SymbolCompletionProvider);
protected override TestComposition GetComposition()
=> base.GetComposition().AddParts(typeof(TestExperimentationService));
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFile(SourceCodeKind sourceCodeKind)
{
await VerifyItemIsAbsentAsync(@"$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData(SourceCodeKind.Regular)]
[InlineData(SourceCodeKind.Script)]
public async Task EmptyFileWithUsing(SourceCodeKind sourceCodeKind)
{
await VerifyItemExistsAsync(@"using System;
$$", @"String", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
await VerifyItemExistsAsync(@"using System;
$$", @"System", expectedDescriptionOrNull: null, sourceCodeKind: sourceCodeKind);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashR()
=> await VerifyItemIsAbsentAsync(@"#r $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterHashLoad()
=> await VerifyItemIsAbsentAsync(@"#load $$", "@System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirective()
{
await VerifyItemIsAbsentAsync(@"using $$", @"String");
await VerifyItemIsAbsentAsync(@"using $$ = System", @"System");
await VerifyItemExistsAsync(@"using $$", @"System");
await VerifyItemExistsAsync(@"using T = $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegion()
{
await VerifyItemIsAbsentAsync(@"class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InactiveRegionWithUsing()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
#if false
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ActiveRegionWithUsing()
{
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"String");
await VerifyItemExistsAsync(@"using System;
class C {
#if true
$$
#endif", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/* $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/* */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment1()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SingleLineXmlComment2()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/// $$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MultiLineXmlComment()
{
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"String");
await VerifyItemIsAbsentAsync(@"using System;
class C {
/** $$ */", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
await VerifyItemExistsAsync(@"using System;
class C {
/** */$$
", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenStringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("string s = \"$$\";")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StringLiteralInDirective()
{
await VerifyItemIsAbsentAsync("#r \"$$\"", "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync("#r \"$$\"", "System", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OpenCharLiteral()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod("char c = '$$")), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute1()
{
await VerifyItemExistsAsync(@"[assembly: $$]", @"System");
await VerifyItemIsAbsentAsync(@"[assembly: $$]", @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssemblyAttribute2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"System");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"[assembly: $$]"), @"AttributeUsage");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SystemAttributeIsNotAnAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"Attribute");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeAttribute()
{
var content = @"[$$]
class CL {}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParamAttribute()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<[A$$]T> {}"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodAttribute()
{
var content = @"class CL {
[$$]
void Method() {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodTypeParamAttribute()
{
var content = @"class CL{
void Method<[A$$]T> () {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodParamAttribute()
{
var content = @"class CL{
void Method ([$$]int i) {}
}";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"AttributeUsage");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_TopLevel()
{
var source = @"namespace $$ { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_EmptyNameSpan_Nested()
{
var source = @";
namespace System
{
namespace $$ { }
}";
await VerifyItemExistsAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers()
{
var source = @"using System;
namespace $$";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelNoPeers_FileScopedNamespace()
{
var source = @"using System;
namespace $$;";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "String", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_TopLevelWithPeer()
{
var source = @"
namespace A { }
namespace $$";
await VerifyItemExistsAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithNoPeers()
{
var source = @"
namespace A
{
namespace $$
}";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B { }
namespace $$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_ExcludesCurrentDeclaration()
{
var source = @"namespace N$$S";
await VerifyItemIsAbsentAsync(source, "NS", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNested()
{
var source = @"
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A
{
namespace $$
{
namespace B { }
}
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Unqualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace $$
namespace C1 { }
}
namespace B.C2 { }
}
namespace A.B.C3 { }";
// Ideally, all the C* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// C1 => A.B.?.C1
// C2 => A.B.B.C2
// C3 => A.A.B.C3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "C1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C3", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
// Because of the above, B does end up in the completion list
// since A.B.B appears to be a peer of the new declaration
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NoPeers()
{
var source = @"namespace A.$$";
await VerifyNoItemsExistAsync(source, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer()
{
var source = @"
namespace A.B { }
namespace A.$$";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_TopLevelWithPeer_FileScopedNamespace()
{
var source = @"
namespace A.B { }
namespace A.$$;";
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_NestedWithPeer()
{
var source = @"
namespace A
{
namespace B.C { }
namespace B.$$
}";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNested()
{
var source = @"
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_WithNestedAndMatchingPeer()
{
var source = @"
namespace A.B { }
namespace A.$$
{
namespace B { }
}
";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemExistsAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_InnerCompletionPosition()
{
var source = @"namespace Sys$$tem.Runtime { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnKeyword()
{
var source = @"name$$space System { }";
await VerifyItemExistsAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_OnNestedKeyword()
{
var source = @"
namespace System
{
name$$space Runtime { }
}";
await VerifyItemIsAbsentAsync(source, "System", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "Runtime", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(7213, "https://github.com/dotnet/roslyn/issues/7213")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceName_Qualified_IncompleteDeclaration()
{
var source = @"
namespace A
{
namespace B
{
namespace C.$$
namespace C.D1 { }
}
namespace B.C.D2 { }
}
namespace A.B.C.D3 { }";
await VerifyItemIsAbsentAsync(source, "A", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "B", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "C", sourceCodeKind: SourceCodeKind.Regular);
// Ideally, all the D* namespaces would be recommended but, because of how the parser
// recovers from the missing braces, they end up with the following qualified names...
//
// D1 => A.B.C.C.?.D1
// D2 => A.B.B.C.D2
// D3 => A.A.B.C.D3
//
// ...none of which are found by the current algorithm.
await VerifyItemIsAbsentAsync(source, "D1", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D2", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(source, "D3", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnderNamespace()
{
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS { $$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType1()
{
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"String");
await VerifyItemIsAbsentAsync(@"namespace NS {
class CL {}
$$", @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OutsideOfType2()
{
var content = @"namespace NS {
class CL {}
$$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideProperty()
{
var content = @"class C
{
private string name;
public string Name
{
set
{
name = $$";
await VerifyItemExistsAsync(content, @"value");
await VerifyItemExistsAsync(content, @"C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterDot()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"[assembly: A.$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingAlias()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"using MyType = $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMember()
{
var content = @"class CL {
$$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteMemberAccessibility()
{
var content = @"class CL {
public $$
";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BadStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = $$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameter()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeTypeParameterList()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionTypePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = ($$)c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObjectCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new $$ [")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StackAllocArrayCreationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = stackalloc $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseTypeOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from $$ c")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join $$ j")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DeclarationStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ i =")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task VariableDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"fixed($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementNoToken()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchDeclaration()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"try {} catch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldDeclaration()
{
var content = @"class CL {
$$ i";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventFieldDeclaration()
{
var content = @"class CL {
event $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclaration()
{
var content = @"class CL {
explicit operator $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConversionOperatorDeclarationNoToken()
{
var content = @"class CL {
explicit $$";
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PropertyDeclaration()
{
var content = @"class CL {
$$ Prop {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EventDeclaration()
{
var content = @"class CL {
event $$ Event {";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IndexerDeclaration()
{
var content = @"class CL {
$$ this";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameter()
{
var content = @"class CL {
void Method($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayType()
{
var content = @"class CL {
$$ [";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PointerType()
{
var content = @"class CL {
$$ *";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableType()
{
var content = @"class CL {
$$ ?";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DelegateDeclaration()
{
var content = @"class CL {
delegate $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodDeclaration()
{
var content = @"class CL {
$$ M(";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OperatorDeclaration()
{
var content = @"class CL {
$$ operator";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", content), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ParenthesizedExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InvocationExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$(")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ElementAccessExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$[")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Argument()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"i[$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CastExpressionExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"(c)$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FromClauseInPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LetClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C let n = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OrderingExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C orderby $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SelectClauseExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C select $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThrowStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"throw $$")), @"System");
}
[WorkItem(760097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/760097")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task YieldReturnStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"yield return $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"foreach(T t in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStatementExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"using($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LockStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"lock($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EqualsValueClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var i = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementInitializersPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementConditionOptPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForStatementIncrementorsPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"for(i=0;i>10;$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DoStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"do {} while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhileStatementConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"while($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ArrayRankSpecifierSizesPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"int [$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PrefixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"+$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task PostfixUnaryExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$++")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ + 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BinaryExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 + $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionLeftPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$ = 1")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AssignmentExpressionRightPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"1 = $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"$$? 1:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenTruePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? $$:")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalExpressionWhenFalsePart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"true? 1:$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseInExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseLeftExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task JoinClauseRightExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C join p in P on id equals $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WhereClauseConditionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C where $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseGroupExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task GroupClauseByExpressionPart()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = from c in C group g by $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IfStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"if ($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchStatement()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"switch($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchLabelCase()
{
var content = @"switch(i) { case $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchPatternLabelCase()
{
var content = @"switch(i) { case $$ when";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionFirstBranch()
{
var content = @"i switch { $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task SwitchExpressionSecondBranch()
{
var content = @"i switch { 1 => true, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternFirstPosition()
{
var content = @"i is ($$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PositionalPatternSecondPosition()
{
var content = @"i is (1, $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternFirstPosition()
{
var content = @"i is { P: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(33915, "https://github.com/dotnet/roslyn/issues/33915")]
public async Task PropertyPatternSecondPosition()
{
var content = @"i is { P1: 1, P2: $$";
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(content)), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InitializerExpression()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"var t = new [] { $$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClause()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseList()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParameterConstraintClauseAnotherWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where T : A where$$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause1()
{
await VerifyItemExistsAsync(@"class CL<T> where $$", @"T");
await VerifyItemExistsAsync(@"class CL{ delegate void F<T>() where $$} ", @"T");
await VerifyItemExistsAsync(@"class CL{ void F<T>() where $$", @"T");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause2()
{
await VerifyItemIsAbsentAsync(@"class CL<T> where $$", @"System");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> where $$"), @"String");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeSymbolOfTypeParameterConstraintClause3()
{
await VerifyItemIsAbsentAsync(@"class CL<T1> { void M<T2> where $$", @"T1");
await VerifyItemExistsAsync(@"class CL<T1> { void M<T2>() where $$", @"T2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseList2()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class CL : B, $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task BaseListWhere()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class CL<T> : B where$$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedName()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"global::$$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedNamespace()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System;", AddInsideMethod(@"S.$$")), @"String");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AliasedType()
=> await VerifyItemExistsAsync(AddUsingDirectives("using S = System.String;", AddInsideMethod(@"S.$$")), @"Empty");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstructorInitializer()
{
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"String");
await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class C { C() : $$"), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"typeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Typeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; typeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"sizeof($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Sizeof2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; sizeof($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default1()
{
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"String");
await VerifyItemExistsAsync(AddUsingDirectives("using System;", AddInsideMethod(@"default($$")), @"System");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Default2()
=> await VerifyItemIsAbsentAsync(AddInsideMethod(@"var x = 0; default($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Checked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; checked($$"), @"x");
[WorkItem(543819, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543819")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Unchecked()
=> await VerifyItemExistsAsync(AddInsideMethod(@"var x = 0; unchecked($$"), @"x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Locals()
=> await VerifyItemExistsAsync(@"class c { void M() { string goo; $$", "goo");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Parameters()
=> await VerifyItemExistsAsync(@"class c { void M(string args) { $$", "args");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LambdaDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = (int _, string _) => 1 + $$", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AnonymousMethodDiscardParameters()
=> await VerifyItemIsAbsentAsync(@"class C { void M() { System.Func<int, string, int> f = delegate(int _, string _) { return 1 + $$ }; } }", "_");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CommonTypesInNewExpressionContext()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"class c { void M() { new $$"), "Exception");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionForUnboundTypes()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M() { goo.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInTypeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { typeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInDefault()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"class c { void M(int x) { default($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInSizeOf()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M(int x) { unsafe { sizeof($$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoParametersInGenericParameterList()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class Generic<T> { void M(int x) { Generic<$$"), "x");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { null.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { true.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { false.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 'c'.$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { """".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { @"""".$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterNumericLiteral()
{
// NOTE: the Completion command handler will suppress this case if the user types '.',
// but we still need to show members if the user specifically invokes statement completion here.
await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { 2.$$"), "Equals");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersAfterParenthesizedNullLiteral()
=> await VerifyItemIsAbsentAsync(AddUsingDirectives("using System;", @"public class C { void M() { (null).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedTrueLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (true).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedFalseLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (false).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedCharLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ('c').$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { ("""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedVerbatimStringLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (@"""").$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterParenthesizedNumericLiteral()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (2).$$"), "Equals");
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MembersAfterArithmeticExpression()
=> await VerifyItemExistsAsync(AddUsingDirectives("using System;", @"public class C { void M() { (1 + 1).$$"), "Equals");
[WorkItem(539332, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539332")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceTypesAvailableInUsingAlias()
=> await VerifyItemExistsAsync(@"using S = System.$$", "String");
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember1()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember2()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
this.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedMember3()
{
var markup = @"
class A
{
private void Hidden() { }
protected void Goo() { }
}
class B : A
{
void Bar()
{
base.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember1()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember2()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
B.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedStaticMember3()
{
var markup = @"
class A
{
private static void Hidden() { }
protected static void Goo() { }
}
class B : A
{
void Bar()
{
A.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Hidden");
await VerifyItemExistsAsync(markup, "Goo");
}
[WorkItem(539812, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539812")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InheritedInstanceAndStaticMembers()
{
var markup = @"
class A
{
private static void HiddenStatic() { }
protected static void GooStatic() { }
private void HiddenInstance() { }
protected void GooInstance() { }
}
class B : A
{
void Bar()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "HiddenStatic");
await VerifyItemExistsAsync(markup, "GooStatic");
await VerifyItemIsAbsentAsync(markup, "HiddenInstance");
await VerifyItemExistsAsync(markup, "GooInstance");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer1()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540155, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540155")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForLoopIndexer2()
{
var markup = @"
class C
{
void M()
{
for (int i = 0; i < 10; $$
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "Dispose");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType1()
{
var markup = @"
class C
{
void M()
{
System.IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType2()
{
var markup = @"
class C
{
void M()
{
(System.IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType3()
{
var markup = @"
using System;
class C
{
void M()
{
IDisposable.$$
";
await VerifyItemExistsAsync(markup, "ReferenceEquals");
}
[WorkItem(540012, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540012")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersAfterType4()
{
var markup = @"
using System;
class C
{
void M()
{
(IDisposable).$$
";
await VerifyItemIsAbsentAsync(markup, "ReferenceEquals");
}
[WorkItem(540197, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540197")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersInClass()
{
var markup = @"
class C<T, R>
{
$$
}
";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[WorkItem(540212, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540212")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInLambda_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
Func<int, int> f = (in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(ref $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(out $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInMethodDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
void M(in $$)
{
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(ref String parameter)
{
M(ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterOutInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(out String parameter)
{
M(out $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(24326, "https://github.com/dotnet/roslyn/issues/24326")]
public async Task AfterInInInvocation_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(in String parameter)
{
M(in $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefExpression_TypeAndVariable()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref var x = ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemExistsAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInStatementContext_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalDeclaration_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int local;
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterRefReadonlyLocalFunction_TypeOnly()
{
var markup = @"
using System;
class C
{
void M(String parameter)
{
ref readonly $$ int Function();
}
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "parameter");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(25569, "https://github.com/dotnet/roslyn/issues/25569")]
public async Task AfterRefReadonlyInMemberContext_TypeOnly()
{
var markup = @"
using System;
class C
{
String field;
ref readonly $$
}
";
await VerifyItemExistsAsync(markup, "String");
await VerifyItemIsAbsentAsync(markup, "field");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType1()
{
var markup = @"
class Q
{
$$
class R
{
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType2()
{
var markup = @"
class Q
{
class R
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType3()
{
var markup = @"
class Q
{
class R
{
}
$$
}
";
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Regular()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
// Top-level statements are not allowed to follow classes, but we still offer it in completion for a few
// reasons:
//
// 1. The code is simpler
// 2. It's a relatively rare coding practice to define types outside of namespaces
// 3. It allows the compiler to produce a better error message when users type things in the wrong order
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType4_Script()
{
var markup = @"
class Q
{
class R
{
}
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
await VerifyItemIsAbsentAsync(markup, "R", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType5()
{
var markup = @"
class Q
{
class R
{
}
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(539217, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539217")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedType6()
{
var markup = @"
class Q
{
class R
{
$$"; // At EOF
await VerifyItemExistsAsync(markup, "Q");
await VerifyItemExistsAsync(markup, "R");
}
[WorkItem(540574, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540574")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenTypeAndLocal()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
public void goo() {
int i = 5;
i.$$
List<string> ml = new List<string>();
}
}";
await VerifyItemExistsAsync(markup, "CompareTo");
}
[WorkItem(21596, "https://github.com/dotnet/roslyn/issues/21596")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AmbiguityBetweenExpressionAndLocalFunctionReturnType()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
AwaitTest test = new AwaitTest();
test.Test1().Wait();
}
}
class AwaitTest
{
List<string> stringList = new List<string>();
public async Task<bool> Test1()
{
stringList.$$
await Test2();
return true;
}
public async Task<bool> Test2()
{
return true;
}
}";
await VerifyItemExistsAsync(markup, "Add");
}
[WorkItem(540750, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540750")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterNewInScript()
{
var markup = @"
using System;
new $$";
await VerifyItemExistsAsync(markup, "String", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(540933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540933")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodsInScript()
{
var markup = @"
using System.Linq;
var a = new int[] { 1, 2 };
a.$$";
await VerifyItemExistsAsync(markup, "ElementAt", displayTextSuffix: "<>", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541019, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541019")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionsInForLoopInitializer()
{
var markup = @"
public class C
{
public void M()
{
int count = 0;
for ($$
";
await VerifyItemExistsAsync(markup, "count");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression1()
{
var markup = @"
public class C
{
public void M()
{
System.Func<int, int> f = arg => { arg = 2; return arg; }.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "ToString");
}
[WorkItem(541108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541108")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaExpression2()
{
var markup = @"
public class C
{
public void M()
{
((System.Func<int, int>)(arg => { arg = 2; return arg; })).$$
}
}
";
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemExistsAsync(markup, "Invoke");
}
[WorkItem(541216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541216")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InMultiLineCommentAtEndOfFile()
{
var markup = @"
using System;
/*$$";
await VerifyItemIsAbsentAsync(markup, "Console", expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(541218, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541218")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeParametersAtEndOfFile()
{
var markup = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Outer<T>
{
class Inner<U>
{
static void F(T t, U u)
{
return;
}
public static void F(T t)
{
Outer<$$";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForCase()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "case 0:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchAbsentForDefaultWhenAbsent()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
case 0:
goto $$";
await VerifyItemIsAbsentAsync(markup, "default:");
}
[WorkItem(552717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelInCaseSwitchPresentForDefault()
{
var markup = @"
class Program
{
static void Main()
{
int x;
switch (x)
{
default:
goto $$";
await VerifyItemExistsAsync(markup, "default");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto1()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto $$";
await VerifyItemExistsAsync(markup, "Goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelAfterGoto2()
{
var markup = @"
class Program
{
static void Main()
{
Goo:
int Goo;
goto Goo $$";
await VerifyItemIsAbsentAsync(markup, "Goo");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeName()
{
var markup = @"
using System;
[$$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifier()
{
var markup = @"
using System;
[assembly:$$
";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeList()
{
var markup = @"
using System;
[CLSCompliant, $$";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameBeforeClass()
{
var markup = @"
using System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterSpecifierBeforeClass()
{
var markup = @"
using System;
[assembly:$$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliant");
await VerifyItemIsAbsentAsync(markup, "CLSCompliantAttribute");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInAttributeArgumentList()
{
var markup = @"
using System;
[CLSCompliant($$
class C { }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542225, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542225")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameInsideClass()
{
var markup = @"
using System;
class C { $$ }";
await VerifyItemExistsAsync(markup, "CLSCompliantAttribute");
await VerifyItemIsAbsentAsync(markup, "CLSCompliant");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName1()
{
var markup = @"
using Alias = System;
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName2()
{
var markup = @"
using Alias = Goo;
namespace Goo { }
[$$
class C { }";
await VerifyItemIsAbsentAsync(markup, "Alias");
}
[WorkItem(542954, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542954")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NamespaceAliasInAttributeName3()
{
var markup = @"
using Alias = Goo;
namespace Goo { class A : System.Attribute { } }
[$$
class C { }";
await VerifyItemExistsAsync(markup, "Alias");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace()
{
var markup = @"
namespace Test
{
class MyAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespace2()
{
var markup = @"
namespace Test
{
namespace Two
{
class MyAttribute : System.Attribute { }
[Test.Two.$$
class Program { }
}
}";
await VerifyItemExistsAsync(markup, "My");
await VerifyItemIsAbsentAsync(markup, "MyAttribute");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterNamespaceWhenSuffixlessFormIsKeyword()
{
var markup = @"
namespace Test
{
class namespaceAttribute : System.Attribute { }
[Test.$$
class Program { }
}";
await VerifyItemExistsAsync(markup, "namespaceAttribute");
await VerifyItemIsAbsentAsync(markup, "namespace");
await VerifyItemIsAbsentAsync(markup, "@namespace");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task KeywordsUsedAsLocals()
{
var markup = @"
class C
{
void M()
{
var error = 0;
var method = 0;
var @int = 0;
Console.Write($$
}
}";
// preprocessor keyword
await VerifyItemExistsAsync(markup, "error");
await VerifyItemIsAbsentAsync(markup, "@error");
// contextual keyword
await VerifyItemExistsAsync(markup, "method");
await VerifyItemIsAbsentAsync(markup, "@method");
// full keyword
await VerifyItemExistsAsync(markup, "@int");
await VerifyItemIsAbsentAsync(markup, "int");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords1()
{
var markup = @"
class C
{
void M()
{
var from = new[]{1,2,3};
var r = from x in $$
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords2()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where $$ == @where.Length
select @from;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545348, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545348")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task QueryContextualKeywords3()
{
var markup = @"
class C
{
void M()
{
var where = new[] { 1, 2, 3 };
var x = from @from in @where
where @from == @where.Length
select $$;
}
}";
await VerifyItemExistsAsync(markup, "@from");
await VerifyItemIsAbsentAsync(markup, "from");
await VerifyItemExistsAsync(markup, "@where");
await VerifyItemIsAbsentAsync(markup, "where");
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAlias()
{
var markup = @"
class MyAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "My", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "MyAttribute", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact]
[WorkItem(545121, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545121")]
[Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeNameAfterGlobalAliasWhenSuffixlessFormIsKeyword()
{
var markup = @"
class namespaceAttribute : System.Attribute { }
[global::$$
class Program { }";
await VerifyItemExistsAsync(markup, "namespaceAttribute", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "namespace", sourceCodeKind: SourceCodeKind.Regular);
await VerifyItemIsAbsentAsync(markup, "@namespace", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(25589, "https://github.com/dotnet/roslyn/issues/25589")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute1()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute2()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace2");
await VerifyItemExistsAsync(markup, "Namespace3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute3()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.$$]";
await VerifyItemExistsAsync(markup, "Namespace4");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute4()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[Namespace1.Namespace3.Namespace4.$$]";
await VerifyItemExistsAsync(markup, "Custom");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithNestedAttribute_NamespaceAlias()
{
var markup = @"
using Namespace1Alias = Namespace1;
using Namespace2Alias = Namespace1.Namespace2;
using Namespace3Alias = Namespace1.Namespace3;
using Namespace4Alias = Namespace1.Namespace3.Namespace4;
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class CustomAttribute : System.Attribute { } }
}
[$$]";
await VerifyItemExistsAsync(markup, "Namespace1Alias");
await VerifyItemIsAbsentAsync(markup, "Namespace2Alias");
await VerifyItemExistsAsync(markup, "Namespace3Alias");
await VerifyItemExistsAsync(markup, "Namespace4Alias");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AttributeSearch_NamespaceWithoutNestedAttribute()
{
var markup = @"
namespace Namespace1
{
namespace Namespace2 { class NonAttribute { } }
namespace Namespace3.Namespace4 { class NonAttribute : System.NonAttribute { } }
}
[$$]";
await VerifyItemIsAbsentAsync(markup, "Namespace1");
}
[WorkItem(542230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542230")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariableInQuerySelect()
{
var markup = @"
using System.Linq;
class P
{
void M()
{
var src = new string[] { ""Goo"", ""Bar"" };
var q = from x in src
select x.$$";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ int"; // 'int' to force this to be parsed as an IsExpression rather than IsPatternExpression
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInIsPatternExpression()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
if (i is $$ 1";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084#issuecomment-370148553")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchPatternCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case $$ when";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInSwitchGotoCase()
{
var markup = @"
class C
{
public const int MAX_SIZE = 10;
void M()
{
int i = 10;
switch (i)
{
case MAX_SIZE:
break;
case GOO:
goto case $$";
await VerifyItemExistsAsync(markup, "MAX_SIZE");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInEnumMember()
{
var markup = @"
class C
{
public const int GOO = 0;
enum E
{
A = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute1()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage($$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute2()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(GOO, $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute3()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(validOn: $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInAttribute4()
{
var markup = @"
class C
{
public const int GOO = 0;
[System.AttributeUsage(AllowMultiple = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInParameterDefaultValue()
{
var markup = @"
class C
{
public const int GOO = 0;
void M(int x = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstField()
{
var markup = @"
class C
{
public const int GOO = 0;
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[WorkItem(542429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542429")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConstantsInConstLocal()
{
var markup = @"
class C
{
public const int GOO = 0;
void M()
{
const int BAR = $$";
await VerifyItemExistsAsync(markup, "GOO");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1Overload()
{
var markup = @"
class C
{
void M(int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ย 1ย {FeaturesResources.overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2Overloads()
{
var markup = @"
class C
{
void M(int i) { }
void M(out int i) { }
void M()
{
$$";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ย 2ย {FeaturesResources.overloads_})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith1GenericOverload()
{
var markup = @"
class C
{
void M<T>(T i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(T i) (+ย 1ย {FeaturesResources.generic_overload})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionWith2GenericOverloads()
{
var markup = @"
class C
{
void M<T>(int i) { }
void M<T>(out int i) { }
void M<T>()
{
$$";
await VerifyItemExistsAsync(markup, "M", displayTextSuffix: "<>", expectedDescriptionOrNull: $"void C.M<T>(int i) (+ย 2ย {FeaturesResources.generic_overloads})");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionNamedGenericType()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "C", displayTextSuffix: "<>", expectedDescriptionOrNull: "class C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionParameter()
{
var markup = @"
class C<T>
{
void M(T goo)
{
$$";
await VerifyItemExistsAsync(markup, "goo", expectedDescriptionOrNull: $"({FeaturesResources.parameter}) T goo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionGenericTypeParameter()
{
var markup = @"
class C<T>
{
void M()
{
$$";
await VerifyItemExistsAsync(markup, "T", expectedDescriptionOrNull: $"T {FeaturesResources.in_} C<T>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionAnonymousType()
{
var markup = @"
class C
{
void M()
{
var a = new { };
$$
";
var expectedDescription =
$@"({FeaturesResources.local_variable}) 'a a
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}";
await VerifyItemExistsAsync(markup, "a", expectedDescription);
}
[WorkItem(543288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543288")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterNewInAnonymousType()
{
var markup = @"
class Program {
string field = 0;
static void Main() {
var an = new { new $$ };
}
}
";
await VerifyItemExistsAsync(markup, "Program");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticMethod()
{
var markup = @"
class C
{
int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
int x = 0;
static int y = $$
}
";
await VerifyItemIsAbsentAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticMethod()
{
var markup = @"
class C
{
static int x = 0;
static void M()
{
$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543601")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsInStaticFieldInitializer()
{
var markup = @"
class C
{
static int x = 0;
static int y = $$
}
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemIsAbsentAsync(markup, "i");
}
[WorkItem(543680, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543680")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticFieldsFromOuterClassInInstanceMethod()
{
var markup = @"
class outer
{
static int i;
class inner
{
void M()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OnlyEnumMembersInEnumMemberAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
x.$$
}
}
";
await VerifyItemExistsAsync(markup, "a");
await VerifyItemExistsAsync(markup, "b");
await VerifyItemExistsAsync(markup, "c");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(543104, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543104")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoEnumMembersInEnumLocalAccess()
{
var markup = @"
class C
{
enum x {a,b,c}
void M()
{
var y = x.a;
y.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "a");
await VerifyItemIsAbsentAsync(markup, "b");
await VerifyItemIsAbsentAsync(markup, "c");
await VerifyItemExistsAsync(markup, "Equals");
}
[WorkItem(529138, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529138")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterLambdaParameterDot()
{
var markup = @"
using System;
using System.Linq;
class A
{
public event Func<String, String> E;
}
class Program
{
static void Main(string[] args)
{
new A().E += ss => ss.$$
}
}
";
await VerifyItemExistsAsync(markup, "Substring");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAtRoot_Interactive()
{
await VerifyItemIsAbsentAsync(
@"$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterClass_Interactive()
{
await VerifyItemIsAbsentAsync(
@"class C { }
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalStatement_Interactive()
{
await VerifyItemIsAbsentAsync(
@"System.Console.WriteLine();
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterGlobalVariableDeclaration_Interactive()
{
await VerifyItemIsAbsentAsync(
@"int i = 0;
$$",
"value",
expectedDescriptionOrNull: null, sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInUsingAlias()
{
await VerifyItemIsAbsentAsync(
@"using Goo = $$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInEmptyStatement()
{
await VerifyItemIsAbsentAsync(AddInsideMethod(
@"$$"),
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideSetter()
{
await VerifyItemExistsAsync(
@"class C {
int Goo {
set {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideAdder()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
add {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueInsideRemover()
{
await VerifyItemExistsAsync(
@"class C {
event int Goo {
remove {
$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterDot()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
this.$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterArrow()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a->$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotAfterColonColon()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
set {
a::$$",
"value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ValueNotInGetter()
{
await VerifyItemIsAbsentAsync(
@"class C {
int Goo {
get {
$$",
"value");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterNullableTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterNullableTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterQuestionMarkAndPartialIdentifierInConditional()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
bool b = false;
int goo = 0;
b? f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAlias()
{
await VerifyItemIsAbsentAsync(
@"using A = System.Int32;
class C {
void M() {
int goo = 0;
A* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterPointerTypeAndPartialIdentifier()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
int goo = 0;
C* f$$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* $$",
"goo");
}
[WorkItem(544205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544205")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsteriskAndPartialIdentifierInMultiplication()
{
await VerifyItemExistsAsync(
@"class C {
void M() {
int i = 0;
int goo = 0;
i* f$$",
"goo");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterEventFieldDeclaredInSameType()
{
await VerifyItemExistsAsync(
@"class C {
public event System.EventHandler E;
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterFullEventDeclaredInSameType()
{
await VerifyItemIsAbsentAsync(
@"class C {
public event System.EventHandler E { add { } remove { } }
void M() {
E.$$",
"Invoke");
}
[WorkItem(543868, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543868")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterEventDeclaredInDifferentType()
{
await VerifyItemIsAbsentAsync(
@"class C {
void M() {
System.Console.CancelKeyPress.$$",
"Invoke");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotInObjectInitializerMemberContext()
{
await VerifyItemIsAbsentAsync(@"
class C
{
public int x, y;
void M()
{
var c = new C { x = 2, y = 3, $$",
"x");
}
[WorkItem(544219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544219")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task AfterPointerMemberAccess()
{
await VerifyItemExistsAsync(@"
struct MyStruct
{
public int MyField;
}
class Program
{
static unsafe void Main(string[] args)
{
MyStruct s = new MyStruct();
MyStruct* ptr = &s;
ptr->$$
}}",
"MyField");
}
// After @ both X and XAttribute are legal. We think this is an edge case in the language and
// are not fixing the bug 11931. This test captures that XAttribute doesn't show up indeed.
[WorkItem(11931, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task VerbatimAttributes()
{
var code = @"
using System;
public class X : Attribute
{ }
public class XAttribute : Attribute
{ }
[@X$$]
class Class3 { }
";
await VerifyItemExistsAsync(code, "X");
await Assert.ThrowsAsync<Xunit.Sdk.TrueException>(() => VerifyItemExistsAsync(code, "XAttribute"));
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; $$
}
}
", "Console");
}
[WorkItem(544928, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544928")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopIncrementor2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (; ; Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer1()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for ($$
}
}
", "Console");
}
[WorkItem(544931, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544931")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task InForLoopInitializer2()
{
await VerifyItemExistsAsync(@"
using System;
class Program
{
static void Main()
{
for (Console.WriteLine(), $$
}
}
", "Console");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclaration()
{
// "int goo = goo = 1" is a legal declaration
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableInItsDeclarator()
{
// "int bar = bar = 1" is legal in a declarator
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$, int baz = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclaration()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
$$
int goo = 0;
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableNotBeforeDeclarator()
{
await VerifyItemIsAbsentAsync(@"
class Program
{
void M()
{
int goo = $$, bar = 0;
}
}", "bar");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAfterDeclarator()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = 0, int bar = $$
}
}", "goo");
}
[WorkItem(10572, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalVariableAsOutArgumentInInitializerExpression()
{
await VerifyItemExistsAsync(@"
class Program
{
void M()
{
int goo = Bar(out $$
}
int Bar(out int x)
{
x = 3;
return 5;
}
}", "goo");
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_OneBrowsableAlways_OneBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Method_Overloads_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
Goo.$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_ExtensionMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_OverloadExtensionMethodAndMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x, int y)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_SameSigExtensionMethodAndMethod_InstanceMethodBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Bar(int x)
{
}
}
public static class GooExtensions
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public static void Bar(this Goo goo, int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task OverriddenSymbolsFilteredFromCompletionList()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
public class B
{
public virtual void Goo(int original)
{
}
}
public class D : B
{
public override void Goo(int derived)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverClass()
{
var markup = @"
class Program
{
void M()
{
C c = new C();
c.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class C
{
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateAlwaysMethodInBrowsableStateNeverBaseClass()
{
var markup = @"
class Program
{
void M()
{
D d = new D();
d.$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public class B
{
public void Goo()
{
}
}
public class D : B
{
public void Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_BrowsableStateNeverMethodsInBaseClass()
{
var markup = @"
class Program : B
{
void M()
{
$$
}
}";
var referencedCode = @"
public class B
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed1()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BrowsableMixed2()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericTypeCausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var ci = new C<int>();
ci.$$
}
}";
var referencedCode = @"
public class C<T>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(int i) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 2,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_GenericType2CausingMethodSignatureEquality_BothBrowsableNever()
{
var markup = @"
class Program
{
void M()
{
var cii = new C<int, int>();
cii.$$
}
}";
var referencedCode = @"
public class C<T, U>
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(T t) { }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo(U u) { }
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 2,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Field_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(522440, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522440")]
[WorkItem(674611, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/674611")]
[WpfFact(Skip = "674611"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_IgnoreBrowsabilityOfGetSetMethods()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
public int Bar {
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
get { return 5; }
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
set { }
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Property_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public int Bar {get; set;}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Always)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
public Goo()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads1()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Constructor_MixedOverloads2()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
public class Goo
{
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo()
{
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
public Goo(int x)
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateNever()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAlways()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Event_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().$$
}
}";
var referencedCode = @"
public delegate void Handler();
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public event Handler Changed;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Changed",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateNever()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAlways()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Delegate_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public event $$
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public delegate void Handler();";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Handler",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateNever_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAlways_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_BrowsableStateAdvanced_FullyQualifiedInUsing()
{
var markup = @"
class Program
{
void M()
{
using (var x = new NS.$$
}
}";
var referencedCode = @"
namespace NS
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public class Goo : System.IDisposable
{
public void Dispose()
{
}
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Class_IgnoreBaseClassBrowsableNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
public class Goo : Bar
{
}
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public class Bar
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Struct_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public struct Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateNever()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAlways()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Enum_BrowsableStateAdvanced()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public enum Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateNever_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAlways_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeclareLocal()
{
var markup = @"
class Program
{
public void M()
{
$$
}
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_Interface_BrowsableStateAdvanced_DeriveFrom()
{
var markup = @"
class Program : $$
{
}";
var referencedCode = @"
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public interface Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Always()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_CrossLanguage_CStoVB_Never()
{
var markup = @"
class Program
{
void M()
{
$$
}
}";
var referencedCode = @"
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Public Class Goo
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 0,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
hideAdvancedMembers: false);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)System.Runtime.InteropServices.TypeLibTypeFlags.FHidden)]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibType_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new $$
}
}";
var referencedCode = @"
[System.Runtime.InteropServices.TypeLibType((short)(System.Runtime.InteropServices.TypeLibTypeFlags.FHidden | System.Runtime.InteropServices.TypeLibTypeFlags.FLicensed))]
public class Goo
{
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Goo",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)System.Runtime.InteropServices.TypeLibFuncFlags.FHidden)]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibFunc_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibFunc((short)(System.Runtime.InteropServices.TypeLibFuncFlags.FHidden | System.Runtime.InteropServices.TypeLibFuncFlags.FReplaceable))]
public void Bar()
{
}
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "Bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_NotHidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_Hidden_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)System.Runtime.InteropServices.TypeLibVarFlags.FHidden)]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EditorBrowsable_TypeLibVar_HiddenAndOtherFlags_Int16Constructor()
{
var markup = @"
class Program
{
void M()
{
new Goo().$$
}
}";
var referencedCode = @"
public class Goo
{
[System.Runtime.InteropServices.TypeLibVar((short)(System.Runtime.InteropServices.TypeLibVarFlags.FHidden | System.Runtime.InteropServices.TypeLibVarFlags.FReplaceable))]
public int bar;
}";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "bar",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 0,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(545557, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545557")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestColorColor1()
{
var markup = @"
class A
{
static void Goo() { }
void Bar() { }
static void Main()
{
A A = new A();
A.$$
}
}";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType1()
{
var markup = @"
using System;
class C
{
public static void Main()
{
$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[WorkItem(545647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545647")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestLaterLocalHidesType2()
{
var markup = @"
using System;
class C
{
public static void Main()
{
C$$
Console.WriteLine();
}
}";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.$$
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await VerifyItemInEditorBrowsableContextsAsync(
markup: markup,
referencedCode: referencedCode,
item: "IndexProp",
expectedSymbolsSameSolution: 1,
expectedSymbolsMetadataReference: 1,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic);
}
[WorkItem(546841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546841")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestDeclarationAmbiguity()
{
var markup = @"
using System;
class Program
{
void Main()
{
Environment.$$
var v;
}
}";
await VerifyItemExistsAsync(markup, "CommandLine");
}
[WorkItem(12781, "https://github.com/dotnet/roslyn/issues/12781")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldDeclarationAmbiguity()
{
var markup = @"
using System;
Environment.$$
var v;
}";
await VerifyItemExistsAsync(markup, "CommandLine", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestCursorOnClassCloseBrace()
{
var markup = @"
using System;
class Outer
{
class Inner { }
$$}";
await VerifyItemExistsAsync(markup, "Inner");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync1()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async $$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AfterAsync2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
public async T$$
}";
await VerifyItemExistsAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAfterAsyncInMethodBody()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void goo()
{
var x = async $$
}
}";
await VerifyItemIsAbsentAsync(markup, "Task");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable1()
{
var markup = @"
class Program
{
void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NotAwaitable2()
{
var markup = @"
class Program
{
async void goo()
{
$$
}
}";
await VerifyItemWithMscorlib45Async(markup, "goo", "void Program.goo()", "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable1()
{
var markup = @"
using System.Threading;
using System.Threading.Tasks;
class Program
{
async Task goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task Awaitable2()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int> goo()
{
$$
}
}";
var description = $@"({CSharpFeaturesResources.awaitable}) Task<int> Program.goo()";
await VerifyItemWithMscorlib45Async(markup, "goo", description, "C#");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpression()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = await request.$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Request();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
// Nothing should be found: no awaiter for request.
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemIsAbsentAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task AwaitableDotsLikeRangeExpressionWithTaskAndParentheses()
{
var markup = @"
using System.IO;
using System.Threading.Tasks;
namespace N
{
class C
{
async Task M()
{
var request = new Task<Request>();
var m = (await request).$$.ReadAsStreamAsync();
}
}
class Request
{
public Task<Stream> ReadAsStreamAsync() => null;
}
}";
await VerifyItemIsAbsentAsync(markup, "Result");
await VerifyItemExistsAsync(markup, "ReadAsStreamAsync");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
$$
}
}";
await VerifyItemExistsAsync(markup, "goo", $"[{CSharpFeaturesResources.deprecated}] void Program.goo()");
}
[WorkItem(568986, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/568986")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoMembersOnDottingIntoUnboundType()
{
var markup = @"
class Program
{
RegistryKey goo;
static void Main(string[] args)
{
goo.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(550717, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/550717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TypeArgumentsInConstraintAfterBaselist()
{
var markup = @"
public class Goo<T> : System.Object where $$
{
}";
await VerifyItemExistsAsync(markup, "T");
}
[WorkItem(647175, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/647175")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoDestructor()
{
var markup = @"
class C
{
~C()
{
$$
";
await VerifyItemIsAbsentAsync(markup, "Finalize");
}
[WorkItem(669624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/669624")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodOnCovariantInterface()
{
var markup = @"
class Schema<T> { }
interface ISet<out T> { }
static class SetMethods
{
public static void ForSchemaSet<T>(this ISet<Schema<T>> set) { }
}
class Context
{
public ISet<T> Set<T>() { return null; }
}
class CustomSchema : Schema<int> { }
class Program
{
static void Main(string[] args)
{
var set = new Context().Set<CustomSchema>();
set.$$
";
await VerifyItemExistsAsync(markup, "ForSchemaSet", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(667752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667752")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ForEachInsideParentheses()
{
var markup = @"
using System;
class C
{
void M()
{
foreach($$)
";
await VerifyItemExistsAsync(markup, "String");
}
[WorkItem(766869, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/766869")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TestFieldInitializerInP2P()
{
var markup = @"
class Class
{
int i = Consts.$$;
}";
var referencedCode = @"
public static class Consts
{
public const int C = 1;
}";
await VerifyItemWithProjectReferenceAsync(markup, referencedCode, "C", 1, LanguageNames.CSharp, LanguageNames.CSharp, false);
}
[WorkItem(834605, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/834605")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowWithEqualsSign()
{
var markup = @"
class c { public int value {set; get; }}
class d
{
void goo()
{
c goo = new c { value$$=
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterThisDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
this.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(825661, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/825661")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInStaticContext()
{
var markup = @"
class C
{
void M1() { }
static void M2()
{
base.$$
}
}";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(7648, "http://github.com/dotnet/roslyn/issues/7648")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NothingAfterBaseDotInScriptContext()
=> await VerifyItemIsAbsentAsync(@"base.$$", @"ToString", sourceCodeKind: SourceCodeKind.Script);
[WorkItem(858086, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/858086")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoNestedTypeWhenDisplayingInstance()
{
var markup = @"
class C
{
class D
{
}
void M2()
{
new C().$$
}
}";
await VerifyItemIsAbsentAsync(markup, "D");
}
[WorkItem(876031, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876031")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CatchVariableInExceptionFilter()
{
var markup = @"
class C
{
void M()
{
try
{
}
catch (System.Exception myExn) when ($$";
await VerifyItemExistsAsync(markup, "myExn");
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterExternAlias()
{
var markup = @"
class C
{
void goo()
{
global::$$
}
}";
await VerifyItemExistsAsync(markup, "System", usePreviousCharAsTrigger: true);
}
[WorkItem(849698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/849698")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExternAliasSuggested()
{
var markup = @"
extern alias Bar;
class C
{
void goo()
{
$$
}
}";
await VerifyItemWithAliasedMetadataReferencesAsync(markup, "Bar", "Bar", 1, "C#", "C#", false);
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ClassDestructor()
{
var markup = @"
class C
{
class N
{
~$$
}
}";
await VerifyItemExistsAsync(markup, "N");
await VerifyItemIsAbsentAsync(markup, "C");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(44423, "https://github.com/dotnet/roslyn/issues/44423")]
public async Task TildeOutsideClass()
{
var markup = @"
class C
{
class N
{
}
}
~$$";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "N");
}
[WorkItem(635957, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635957")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StructDestructor()
{
var markup = @"
struct C
{
~$$
}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData("record")]
[InlineData("record class")]
public async Task RecordDestructor(string record)
{
var markup = $@"
{record} C
{{
~$$
}}";
await VerifyItemExistsAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RecordStructDestructor()
{
var markup = $@"
record struct C
{{
~$$
}}";
await VerifyItemIsAbsentAsync(markup, "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
int x;
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
await VerifyItemInLinkedFilesAsync(markup, "x", $"({FeaturesResources.field}) int C.x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.field}) int C.x\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UnionOfItemsFromBothContexts()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
class G
{
public void DoGStuff() {}
}
#endif
void goo()
{
new G().$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void G.DoGStuff()\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "DoGStuff", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
int xyz;
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
#if PROJ1
int xyz;
#endif
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.local_variable}) int xyz\r\n\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}";
await VerifyItemInLinkedFilesAsync(markup, "xyz", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void M()
{
LABEL: int xyz;
goto $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.label}) LABEL";
await VerifyItemInLinkedFilesAsync(markup, "LABEL", expectedDescription);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] { 1, 2, 3 } select $$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({FeaturesResources.range_variable}) ? y";
await VerifyItemInLinkedFilesAsync(markup, "y", expectedDescription);
}
[WorkItem(1063403, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1063403")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ExtensionMethod2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""TWO"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
void Shared()
{
this.$$
}
}
public static class Extensions
{
#if TWO
public static void Do (this C c, string x)
{
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""ONE"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({CSharpFeaturesResources.extension}) void C.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
void Shared()
{
var x = GetThing();
x.$$
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyItemInLinkedFilesAsync(markup, "Do", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if ONE
public int x;
#endif
#if TWO
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = $"({ FeaturesResources.field }) int C.x";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SharedProjectFieldAndPropertiesTreatedAsIdentical2()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""CurrentDocument.cs""><![CDATA[
class C
{
#if TWO
public int x;
#endif
#if ONE
public int x {get; set;}
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""CurrentDocument.cs""/>
</Project>
</Workspace>";
var expectedDescription = "int C.x { get; set; }";
await VerifyItemInLinkedFilesAsync(markup, "x", expectedDescription);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessWalkUp()
{
var markup = @"
public class B
{
public A BA;
public B BB;
}
class A
{
public A AA;
public A AB;
public int? x;
public void goo()
{
A a = null;
var q = a?.$$AB.BA.AB.BA;
}
}";
await VerifyItemExistsAsync(markup, "AA");
await VerifyItemExistsAsync(markup, "AB");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
A a = null;
var q = a?.s?.$$;
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrapped2()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S? s;
public void goo()
{
var q = s?.$$i?.ToString();
}
}";
await VerifyItemExistsAsync(markup, "i");
await VerifyItemIsAbsentAsync(markup, "value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ConditionalAccessNullableIsUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt?.$$
}
}
";
await VerifyItemExistsAsync(markup, "Day");
await VerifyItemIsAbsentAsync(markup, "Value");
}
[WorkItem(54361, "https://github.com/dotnet/roslyn/issues/54361")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NullableIsNotUnwrappedOnParameter()
{
var markup = @"
class A
{
void M(System.DateTime? dt)
{
dt.$$
}
}
";
await VerifyItemExistsAsync(markup, "Value");
await VerifyItemIsAbsentAsync(markup, "Day");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionAfterConditionalIndexing()
{
var markup = @"
public struct S
{
public int? i;
}
class A
{
public S[] s;
public void goo()
{
A a = null;
var q = a?.s?[$$;
}
}";
await VerifyItemExistsAsync(markup, "System");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses1()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.$$b?.c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses2()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.$$c?.d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "c");
}
[WorkItem(1109319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1109319")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinChainOfConditionalAccesses3()
{
var markup = @"
class Program
{
static void Main(string[] args)
{
A a;
var x = a?.b?.c?.$$d.e;
}
}
class A { public B b; }
class B { public C c; }
class C { public D d; }
class D { public int e; }";
await VerifyItemExistsAsync(markup, "d");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnSelf()
{
var markup = @"using System;
[My]
class X
{
[My$$]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[WorkItem(843466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/843466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NestedAttributeAccessibleOnOuterType()
{
var markup = @"using System;
[My]
class Y
{
}
[$$]
class X
{
[My]
class MyAttribute : Attribute
{
}
}";
await VerifyItemExistsAsync(markup, "My");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType()
{
var markup = @"abstract class Test
{
private int _field;
public sealed class InnerTest : Test
{
public void SomeTest()
{
$$
}
}
}";
await VerifyItemExistsAsync(markup, "_field");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType2()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
$$ // M recommended and accessible
}
class NN
{
void Test2()
{
// M inaccessible and not recommended
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType3()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN
{
void Test2()
{
$$ // M inaccessible and not recommended
}
}
}
}";
await VerifyItemIsAbsentAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType4()
{
var markup = @"class C<T>
{
void M() { }
class N : C<int>
{
void Test()
{
M(); // M recommended and accessible
}
class NN : N
{
void Test2()
{
$$ // M accessible and recommended.
}
}
}
}";
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType5()
{
var markup = @"
class D
{
public void Q() { }
}
class C<T> : D
{
class N
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Q");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersFromBaseOuterType6()
{
var markup = @"
class Base<T>
{
public int X;
}
class Derived : Base<int>
{
class Nested
{
void Test()
{
$$
}
}
}";
await VerifyItemIsAbsentAsync(markup, "X");
}
[WorkItem(983367, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/983367")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoTypeParametersDefinedInCrefs()
{
var markup = @"using System;
/// <see cref=""Program{T$$}""/>
class Program<T> { }";
await VerifyItemIsAbsentAsync(markup, "T");
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList1()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(988025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/988025")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ShowTypesInGenericMethodTypeParameterList2()
{
var markup = @"
class Class1<T, D>
{
public static Class1<T, D> Create() { return null; }
}
static class Class2
{
public static void Test<T,D>(this Class1<T, D> arg)
{
}
}
class Program
{
static void Main(string[] args)
{
Class1<string, int>.Create().Test<string,$$
}
}
";
await VerifyItemExistsAsync(markup, "Class1", displayTextSuffix: "<>", sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task DescriptionInAliasedType()
{
var markup = @"
using IAlias = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C
{
I$$
}
";
await VerifyItemExistsAsync(markup, "IAlias", expectedDescriptionOrNull: "interface IGoo\r\nsummary for interface IGoo");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task WithinNameOf()
{
var markup = @"
class C
{
void goo()
{
var x = nameof($$)
}
}
";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y1");
}
[WorkItem(997410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/997410")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMemberInNameOfInStaticContext()
{
var markup = @"
class C
{
int y1 = 15;
static int y2 = 1;
static string x = nameof($$
";
await VerifyItemExistsAsync(markup, "y2");
}
[WorkItem(883293, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/883293")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IncompleteDeclarationExpressionType()
{
var markup = @"
using System;
class C
{
void goo()
{
var x = Console.$$
var y = 3;
}
}
";
await VerifyItemExistsAsync(markup, "WriteLine");
}
[WorkItem(1024380, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1024380")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticAndInstanceInNameOf()
{
var markup = @"
using System;
class C
{
class D
{
public int x;
public static int y;
}
void goo()
{
var z = nameof(C.D.$$
}
}
";
await VerifyItemExistsAsync(markup, "x");
await VerifyItemExistsAsync(markup, "y");
}
[WorkItem(1663, "https://github.com/dotnet/roslyn/issues/1663")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForLocals()
{
var markup = @"class C
{
void M()
{
var x = nameof(T.z.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes2()
{
var markup = @"class C
{
void M()
{
var x = nameof(U.$$)
}
}
public class T
{
public U z;
}
public class U
{
public int nope;
}
";
await VerifyItemExistsAsync(markup, "nope");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes3()
{
var markup = @"class C
{
void M()
{
var x = nameof(N.$$)
}
}
namespace N
{
public class U
{
public int nope;
}
} ";
await VerifyItemExistsAsync(markup, "U");
}
[WorkItem(1029522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1029522")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NameOfMembersListedForNamespacesAndTypes4()
{
var markup = @"
using z = System;
class C
{
void M()
{
var x = nameof(z.$$)
}
}
";
await VerifyItemExistsAsync(markup, "Console");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings1()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$
";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings2()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{$$}"";
}
}";
await VerifyItemExistsAsync(markup, "a");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings3()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings4()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings5()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$
";
await VerifyItemExistsAsync(markup, "b");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InterpolatedStrings6()
{
var markup = @"
class C
{
void M()
{
var a = ""Hello"";
var b = ""World"";
var c = $@""{a}, {$$}"";
}
}";
await VerifyItemExistsAsync(markup, "b");
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBeforeFirstStringHole()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}$$\{1}\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotBetweenStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}$$\{2}"""));
}
[WorkItem(1064811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1064811")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotAfterStringHoles()
{
await VerifyNoItemsExistAsync(AddInsideMethod(
@"var x = ""\{0}\{1}\{2}$$"""));
}
[WorkItem(1087171, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087171")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task CompletionAfterTypeOfGetType()
{
await VerifyItemExistsAsync(AddInsideMethod(
"typeof(int).GetType().$$"), "GUID");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives1()
{
var markup = @"
using $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives2()
{
var markup = @"
using N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemIsAbsentAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives3()
{
var markup = @"
using G = $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives4()
{
var markup = @"
using G = N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives5()
{
var markup = @"
using static $$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingDirectives6()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemExistsAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates1()
{
var markup = @"
using static $$
class A { }
delegate void B();
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "B");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowDelegates2()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
delegate void D();
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "D");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces1()
{
var markup = @"
using static N.$$
class A { }
static class B { }
namespace N
{
class C { }
interface I { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "C");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "M");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticDoesNotShowInterfaces2()
{
var markup = @"
using static $$
class A { }
interface I { }
namespace N
{
class C { }
static class D { }
namespace M { }
}";
await VerifyItemExistsAsync(markup, "A");
await VerifyItemIsAbsentAsync(markup, "I");
await VerifyItemExistsAsync(markup, "N");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods1()
{
var markup = @"
using static A;
using static B;
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods2()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods3()
{
var markup = @"
using N;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods4()
{
var markup = @"
using static N.A;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods5()
{
var markup = @"
using static N.A;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemIsAbsentAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods6()
{
var markup = @"
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$
}
}
";
await VerifyItemIsAbsentAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task UsingStaticAndExtensionMethods7()
{
var markup = @"
using N;
using static N.B;
namespace N
{
static class A
{
public static void Goo(this string s) { }
}
static class B
{
public static void Bar(this string s) { }
}
}
class C
{
void M()
{
string s;
s.$$;
}
}
";
await VerifyItemExistsAsync(markup, "Goo");
await VerifyItemExistsAsync(markup, "Bar");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinSameClassOfferedForCompletion()
{
var markup = @"
public static class Test
{
static void TestB()
{
$$
}
static void TestA(this string s) { }
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[WorkItem(7932, "https://github.com/dotnet/roslyn/issues/7932")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExtensionMethodWithinParentClassOfferedForCompletion()
{
var markup = @"
public static class Parent
{
static void TestA(this string s) { }
static void TestC(string s) { }
public static class Test
{
static void TestB()
{
$$
}
}
}
";
await VerifyItemExistsAsync(markup, "TestA");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter1_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch when $$
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when ($$
";
await VerifyItemExistsAsync(markup, "x");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExceptionFilter2_NotBeforeOpenParen()
{
var markup = @"
using System;
class C
{
void M(bool x)
{
try
{
}
catch (Exception ex) when $$
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause1()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case 1 when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(25084, "https://github.com/dotnet/roslyn/issues/25084")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task SwitchCaseWhenClause2()
{
var markup = @"
class C
{
void M(bool x)
{
switch (1)
{
case int i when $$
";
await VerifyItemExistsAsync(markup, "x");
}
[WorkItem(717, "https://github.com/dotnet/roslyn/issues/717")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ExpressionContextCompletionWithinCast()
{
var markup = @"
class Program
{
void M()
{
for (int i = 0; i < 5; i++)
{
var x = ($$)
var y = 1;
}
}
}
";
await VerifyItemExistsAsync(markup, "i");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInPropertyInitializer()
{
var markup = @"
class A {
int abc;
int B { get; } = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[WorkItem(1277, "https://github.com/dotnet/roslyn/issues/1277")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInPropertyInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoInstanceMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
Action abc;
event Action B = $$
}
";
await VerifyItemIsAbsentAsync(markup, "abc");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task StaticMembersInFieldLikeEventInitializer()
{
var markup = @"
class A {
static Action s_abc;
event Action B = $$
}
";
await VerifyItemExistsAsync(markup, "s_abc");
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldInitializer()
{
var markup = @"
int aaa = 1;
int bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(5069, "https://github.com/dotnet/roslyn/issues/5069")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task InstanceMembersInTopLevelFieldLikeEventInitializer()
{
var markup = @"
Action aaa = null;
event Action bbb = $$
";
await VerifyItemExistsAsync(markup, "aaa", sourceCodeKind: SourceCodeKind.Script);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes1()
{
var markup = @"
using A = System
class C
{
A?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes2()
{
var markup = @"
class C
{
System?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(33, "https://github.com/dotnet/roslyn/issues/33")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoConditionalAccessCompletionOnTypes3()
{
var markup = @"
class C
{
System.Console?.$$
}
";
await VerifyNoItemsExistAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInIncompletePropertyDeclaration()
{
var markup = @"
class Class1
{
public string Property1 { get; set; }
}
class Class2
{
public string Property { get { return this.Source.$$
public Class1 Source { get; set; }
}";
await VerifyItemExistsAsync(markup, "Property1");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task NoCompletionInShebangComments()
{
await VerifyNoItemsExistAsync("#!$$", sourceCodeKind: SourceCodeKind.Script);
await VerifyNoItemsExistAsync("#! S$$", sourceCodeKind: SourceCodeKind.Script, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompoundNameTargetTypePreselection()
{
var markup = @"
class Class1
{
void goo()
{
int x = 3;
string y = x.$$
}
}";
await VerifyItemExistsAsync(markup, "ToString", matchPriority: SymbolMatchPriority.PreferEventOrMethod);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer1()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargetTypeInCollectionInitializer2()
{
var markup = @"
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
int z;
string q;
List<int> x = new List<int>() { 1, $$ }
}
}";
await VerifyItemExistsAsync(markup, "z", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer1()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TargeTypeInObjectInitializer2()
{
var markup = @"
class C
{
public int X { get; set; }
public int Y { get; set; }
void goo()
{
int i;
var c = new C() { X = 1, Y = $$ }
}
}";
await VerifyItemExistsAsync(markup, "i", matchPriority: SymbolMatchPriority.PreferLocalOrParameterOrRangeVariable);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElements()
{
var markup = @"
class C
{
void goo()
{
var t = (Alice: 1, Item2: 2, ITEM3: 3, 4, 5, 6, 7, 8, Bob: 9);
t.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
await VerifyItemExistsAsync(markup, "Alice");
await VerifyItemExistsAsync(markup, "Bob");
await VerifyItemExistsAsync(markup, "CompareTo");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "GetType");
await VerifyItemExistsAsync(markup, "Item2");
await VerifyItemExistsAsync(markup, "ITEM3");
for (var i = 4; i <= 8; i++)
{
await VerifyItemExistsAsync(markup, "Item" + i);
}
await VerifyItemExistsAsync(markup, "ToString");
await VerifyItemIsAbsentAsync(markup, "Item1");
await VerifyItemIsAbsentAsync(markup, "Item9");
await VerifyItemIsAbsentAsync(markup, "Rest");
await VerifyItemIsAbsentAsync(markup, "Item3");
}
[WorkItem(14546, "https://github.com/dotnet/roslyn/issues/14546")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleElementsCompletionOffMethodGroup()
{
var markup = @"
class C
{
void goo()
{
new object().ToString.$$
}
}" + TestResources.NetFX.ValueTuple.tuplelib_cs;
// should not crash
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task NoCompletionInLocalFuncGenericParamList()
{
var markup = @"
class C
{
void M()
{
int Local<$$";
await VerifyNoItemsExistAsync(markup);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
[WorkItem(13480, "https://github.com/dotnet/roslyn/issues/13480")]
public async Task CompletionForAwaitWithoutAsync()
{
var markup = @"
class C
{
void M()
{
await Local<$$";
await VerifyAnyItemExistsAsync(markup);
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel1()
{
await VerifyItemExistsAsync(@"
class C
{
($$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel2()
{
await VerifyItemExistsAsync(@"
class C
{
($$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel3()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeAtMemberLevel4()
{
await VerifyItemExistsAsync(@"
class C
{
(C, $$)
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInForeach()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
foreach ((C, $$
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInParameterList()
{
await VerifyItemExistsAsync(@"
class C
{
void M((C, $$)
{
}
}", "C");
}
[WorkItem(14127, "https://github.com/dotnet/roslyn/issues/14127")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task TupleTypeInNameOf()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
var x = nameof((C, $$
}
}", "C");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription()
{
await VerifyItemExistsAsync(@"
class C
{
void M()
{
void Local() { }
$$
}
}", "Local", "void Local()");
}
[WorkItem(14163, "https://github.com/dotnet/roslyn/issues/14163")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionDescription2()
{
await VerifyItemExistsAsync(@"
using System;
class C
{
class var { }
void M()
{
Action<int> Local(string x, ref var @class, params Func<int, string> f)
{
return () => 0;
}
$$
}
}", "Local", "Action<int> Local(string x, ref var @class, params Func<int, string> f)");
}
[WorkItem(18359, "https://github.com/dotnet/roslyn/issues/18359")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterDot()
{
var markup =
@"namespace ConsoleApplication253
{
class Program
{
static void Main(string[] args)
{
M(E.$$)
}
static void M(E e) { }
}
enum E
{
A,
B,
}
}
";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup1()
{
var markup =
@"namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
Main.$$
}
}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup2()
{
var markup =
@"class C {
void M<T>() {M<C>.$$ }
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(8321, "https://github.com/dotnet/roslyn/issues/8321")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task NotOnMethodGroup3()
{
var markup =
@"class C {
void M() {M.$$}
}
";
await VerifyNoItemsExistAsync(markup);
}
[WorkItem(420697, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=420697&_a=edit")]
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/21766"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DoNotCrashInExtensionMethoWithExpressionBodiedMember()
{
var markup =
@"public static class Extensions { public static T Get<T>(this object o) => $$}
";
await VerifyItemExistsAsync(markup, "o");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task EnumConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Enum");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task DelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "Delegate");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task MulticastDelegateConstraint()
{
var markup =
@"public class X<T> where T : System.$$
";
await VerifyItemExistsAsync(markup, "MulticastDelegate");
}
private static string CreateThenIncludeTestCode(string lambdaExpressionString, string methodDeclarationString)
{
var template = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ThenIncludeIntellisenseBug
{
class Program
{
static void Main(string[] args)
{
var registrations = new List<Registration>().AsQueryable();
var reg = registrations.Include(r => r.Activities).ThenInclude([1]);
}
}
internal class Registration
{
public ICollection<Activity> Activities { get; set; }
}
public class Activity
{
public Task Task { get; set; }
}
public class Task
{
public string Name { get; set; }
}
public interface IIncludableQueryable<out TEntity, out TProperty> : IQueryable<TEntity>
{
}
public static class EntityFrameworkQuerybleExtensions
{
public static IIncludableQueryable<TEntity, TProperty> Include<TEntity, TProperty>(
this IQueryable<TEntity> source,
Expression<Func<TEntity, TProperty>> navigationPropertyPath)
where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
[2]
}
}";
return template.Replace("[1]", lambdaExpressionString).Replace("[2]", methodDeclarationString);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenInclude()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoExpression()
{
var markup = CreateThenIncludeTestCode("b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Func<TPreviousProperty, TProperty> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgument()
{
var markup = CreateThenIncludeTestCode("0, b => b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambda()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$)",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentNoOverlap()
{
var markup = CreateThenIncludeTestCode("b => b.Task, b =>b.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath,
Expression<Func<TPreviousProperty, TProperty>> anotherNavigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeSecondArgumentAndMultiArgumentLambdaWithNoLambdaOverlap()
{
var markup = CreateThenIncludeTestCode("0, (a,b,c) => c.$$",
@"
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, ICollection<TPreviousProperty>> source,
int a,
Expression<Func<string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
int a,
Expression<Func<string, string, TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemIsAbsentAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/35100"), Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeGenericAndNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<TEntity, TProperty> ThenInclude<TEntity, TPreviousProperty, TProperty>(
this IIncludableQueryable<TEntity, TPreviousProperty> source,
Expression<Func<TPreviousProperty, TProperty>> navigationPropertyPath) where TEntity : class
{
return default(IIncludableQueryable<TEntity, TProperty>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ThenIncludeNoGenericOverloads()
{
var markup = CreateThenIncludeTestCode("c => c.$$",
@"
public static IIncludableQueryable<Registration, Task> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<Activity, Task> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Task>);
}
public static IIncludableQueryable<Registration, Activity> ThenInclude(
this IIncludableQueryable<Registration, ICollection<Activity>> source,
Func<ICollection<Activity>, Activity> navigationPropertyPath)
{
return default(IIncludableQueryable<Registration, Activity>);
}
");
await VerifyItemExistsAsync(markup, "Task");
await VerifyItemExistsAsync(markup, "FirstOrDefault", displayTextSuffix: "<>");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaWithOverloads()
{
var markup = @"
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace ClassLibrary1
{
class SomeItem
{
public string A;
public int B;
}
class SomeCollection<T> : List<T>
{
public virtual SomeCollection<T> Include(string path) => null;
}
static class Extensions
{
public static IList<T> Include<T, TProperty>(this IList<T> source, Expression<Func<T, TProperty>> path)
=> null;
public static IList Include(this IList source, string path) => null;
public static IList<T> Include<T>(this IList<T> source, string path) => null;
}
class Program
{
void M(SomeCollection<SomeItem> c)
{
var a = from m in c.Include(t => t.$$);
}
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "A");
await VerifyItemExistsAsync(markup, "B");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads2()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(string s) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads3()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M((int p) => p.$$);
}
}";
await VerifyItemIsAbsentAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1056325, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1056325")]
public async Task CompletionForLambdaWithOverloads4()
{
var markup = @"
using System;
class C
{
void M(Action<int> a) { }
void M(Action<string> a) { }
void Test()
{
M(p => p.$$);
}
}";
await VerifyItemExistsAsync(markup, "Substring");
await VerifyItemExistsAsync(markup, "GetTypeCode");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParameters()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new List<Product>(), arg => arg.$$);
}
static void Create<T>(List<T> list, Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1, Product2>(), arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersAndOverloads2()
{
var markup = @"
using System;
using System.Collections.Generic;
class Program
{
static void M()
{
Create(new Dictionary<Product1,Product2>(),arg => arg.$$);
}
static void Create<T, U>(Dictionary<T, U> list, Action<T> expression) { }
static void Create<T, U>(Dictionary<U, T> list, Action<T> expression) { }
static void Create(Dictionary<Product1, Product2> list, Action<Product3> expression) { }
}
class Product1 { public void MyProperty1() { } }
class Product2 { public void MyProperty2() { } }
class Product3 { public void MyProperty3() { } }";
await VerifyItemExistsAsync(markup, "MyProperty1");
await VerifyItemExistsAsync(markup, "MyProperty2");
await VerifyItemExistsAsync(markup, "MyProperty3");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClass()
{
var markup = @"
using System;
class Program<T>
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemIsAbsentAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnType()
{
var markup = @"
using System;
class Program<T> where T : Product
{
static void M()
{
Create(arg => arg.$$);
}
static void Create(Action<T> expression) { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(42997, "https://github.com/dotnet/roslyn/issues/42997")]
public async Task CompletionForLambdaWithTypeParametersFromClassWithConstraintOnMethod()
{
var markup = @"
using System;
class Program
{
static void M()
{
Create(arg => arg.$$);
}
static void Create<T>(Action<T> expression) where T : Product { }
}
class Product { public void MyProperty() { } }";
await VerifyItemExistsAsync(markup, "GetHashCode");
await VerifyItemExistsAsync(markup, "MyProperty");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter1()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x = 7, Action<string> y = null) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(40216, "https://github.com/dotnet/roslyn/issues/40216")]
public async Task CompletionForLambdaPassedAsNamedArgumentAtDifferentPositionFromCorrespondingParameter2()
{
var markup = @"
using System;
class C
{
void Test()
{
X(y: t => Console.WriteLine(t.$$));
}
void X(int x, int z, Action<string> y) { }
}
";
await VerifyItemExistsAsync(markup, "Length");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_NonInteractive()
{
var markup = @"
using System;
static class CExtensions
{
public static void X(this C x, Action<string> y) { }
}
class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Regular);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionForLambdaPassedAsArgumentInReducedExtensionMethod_Interactive()
{
var markup = @"
using System;
public static void X(this C x, Action<string> y) { }
public class C
{
void Test()
{
new C().X(t => Console.WriteLine(t.$$));
}
}
";
await VerifyItemExistsAsync(markup, "Length", sourceCodeKind: SourceCodeKind.Script);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithNonFunctionsAsArguments()
{
var markup = @"
using System;
class c
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> configure)
{
var builder = new Builder();
configure(builder);
}
}
class Builder
{
public int Something { get; set; }
}";
await VerifyItemExistsAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAsArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1(Uri u);
public delegate void Delegate2(Guid g);
public void M(Delegate1 d) { }
public void M(Delegate2 d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Uri
await VerifyItemExistsAsync(markup, "AbsoluteUri");
await VerifyItemExistsAsync(markup, "Fragment");
await VerifyItemExistsAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodsWithDelegatesAndReversingArguments()
{
var markup = @"
using System;
class Program
{
public delegate void Delegate1<T1,T2>(T2 t2, T1 t1);
public delegate void Delegate2<T1,T2>(T2 t2, int g, T1 t1);
public void M(Delegate1<Uri,Guid> d) { }
public void M(Delegate2<Uri,Guid> d) { }
public void Test()
{
M(d => d.$$)
}
}";
// Guid
await VerifyItemExistsAsync(markup, "ToByteArray");
// Should not appear for Uri
await VerifyItemIsAbsentAsync(markup, "AbsoluteUri");
await VerifyItemIsAbsentAsync(markup, "Fragment");
await VerifyItemIsAbsentAsync(markup, "Query");
// Should not appear for Delegate
await VerifyItemIsAbsentAsync(markup, "BeginInvoke");
await VerifyItemIsAbsentAsync(markup, "Clone");
await VerifyItemIsAbsentAsync(markup, "Method");
await VerifyItemIsAbsentAsync(markup, "Target");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsBeforeParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(builder =>
{
builder.$$
});
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "AnotherSomething");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "Something");
}
[WorkItem(36029, "https://github.com/dotnet/roslyn/issues/36029")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionInsideMethodWithParamsInParams()
{
var markup = @"
using System;
class C
{
void M()
{
Goo(b0 => { }, b1 => {}, b2 => { b2.$$ });
}
void Goo(Action<Builder> action, params Action<AnotherBuilder>[] otherActions)
{
}
}
class Builder
{
public int Something { get; set; }
};
class AnotherBuilder
{
public int AnotherSomething { get; set; }
}";
await VerifyItemIsAbsentAsync(markup, "Something");
await VerifyItemIsAbsentAsync(markup, "FirstOrDefault");
await VerifyItemExistsAsync(markup, "AnotherSomething");
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilterWithExperimentEnabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestNoTargetTypeFilterWithExperimentDisabled()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, false);
var markup =
@"public class C
{
int intField;
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "intField",
matchingFilters: new List<CompletionFilter> { FilterSet.FieldFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotOnObjectMembers()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(int x)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "GetHashCode",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeFilter_NotNamedTypes()
{
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
@"public class C
{
void M(C c)
{
M($$);
}
}";
await VerifyItemExistsAsync(
markup, "c",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter, FilterSet.TargetTypedFilter });
await VerifyItemExistsAsync(
markup, "C",
matchingFilters: new List<CompletionFilter> { FilterSet.ClassFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionShouldNotProvideExtensionMethodsIfTypeConstraintDoesNotMatch()
{
var markup = @"
public static class Ext
{
public static void DoSomething<T>(this T thing, string s) where T : class, I
{
}
}
public interface I
{
}
public class C
{
public void M(string s)
{
this.$$
}
}";
await VerifyItemExistsAsync(markup, "M");
await VerifyItemExistsAsync(markup, "Equals");
await VerifyItemIsAbsentAsync(markup, "DoSomething", displayTextSuffix: "<>");
}
[WorkItem(38074, "https://github.com/dotnet/roslyn/issues/38074")]
[Fact]
[Trait(Traits.Feature, Traits.Features.Completion)]
[CompilerTrait(CompilerFeature.LocalFunctions)]
public async Task LocalFunctionInStaticMethod()
{
await VerifyItemExistsAsync(@"
class C
{
static void M()
{
void Local() { }
$$
}
}", "Local");
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
[WorkItem(1152109, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1152109")]
public async Task NoItemWithEmptyDisplayName()
{
var markup = @"
class C
{
static void M()
{
int$$
}
}
";
await VerifyItemIsAbsentAsync(
markup, "",
matchingFilters: new List<CompletionFilter> { FilterSet.LocalAndParameterFilter });
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
F$$
}
private void Foo(int i)
{
}
private void Foo(int i, int c)
{
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(){commitChar}
}}
private void Foo(int i)
{{
}}
private void Foo(int i, int c)
{{
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithSemicolonInNestedMethod(char commitChar)
{
var markup = @"
class Program
{
private void Bar()
{
Foo(F$$);
}
private int Foo(int i)
{
return 1;
}
}";
var expected = $@"
class Program
{{
private void Bar()
{{
Foo(Foo(){commitChar});
}}
private int Foo(int i)
{{
return 1;
}}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForDelegateInferredType(char commitChar)
{
var markup = @"
using System;
class Program
{
private void Bar()
{
Bar2(F$$);
}
private void Foo()
{
}
void Bar2(Action t) { }
}";
var expected = $@"
using System;
class Program
{{
private void Bar()
{{
Bar2(Foo{commitChar});
}}
private void Foo()
{{
}}
void Bar2(Action t) {{ }}
}}";
await VerifyProviderCommitAsync(markup, "Foo", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForConstructor(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = new P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = new Program(){commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCharForTypeUnderNonObjectCreationContext(char commitChar)
{
var markup = @"
class Program
{
private static void Bar()
{
var o = P$$
}
}";
var expected = $@"
class Program
{{
private static void Bar()
{{
var o = Program{commitChar}
}}
}}";
await VerifyProviderCommitAsync(markup, "Program", expected, commitChar: commitChar);
}
[Theory, Trait(Traits.Feature, Traits.Features.Completion)]
[InlineData('.')]
[InlineData(';')]
public async Task CompletionWithCustomizedCommitCharForAliasConstructor(char commitChar)
{
var markup = @"
using String2 = System.String;
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = new S$$
}
}
}";
var expected = $@"
using String2 = System.String;
namespace Bar1
{{
class Program
{{
private static void Bar()
{{
var o = new String2(){commitChar}
}}
}}
}}";
await VerifyProviderCommitAsync(markup, "String2", expected, commitChar: commitChar);
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task CompletionWithSemicolonUnderNameofContext()
{
var markup = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(B$$)
}
}
}";
var expected = @"
namespace Bar1
{
class Program
{
private static void Bar()
{
var o = nameof(Bar;)
}
}
}";
await VerifyProviderCommitAsync(markup, "Bar", expected, commitChar: ';');
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPatternMatchWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m is RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterPropertyPatternMatch()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
public RankedMusicians R;
void M(C m)
{
if (m is { R: RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ChildClassAfterPatternMatch()
{
var markup =
@"namespace N
{
public class D { public class E { } }
class C
{
void M(object m)
{
if (m is D.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "E");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpression()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49072, "https://github.com/dotnet/roslyn/issues/49072")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task EnumMemberAfterBinaryExpressionWithDeclaration()
{
var markup =
@"namespace N
{
enum RankedMusicians
{
BillyJoel,
EveryoneElse
}
class C
{
void M(RankedMusicians m)
{
if (m == RankedMusicians.$$ r)
{
}
}
}
}";
// VerifyItemExistsAsync also tests with the item typed.
await VerifyItemExistsAsync(markup, "BillyJoel");
await VerifyItemExistsAsync(markup, "EveryoneElse");
await VerifyItemIsAbsentAsync(markup, "Equals");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task ObsoleteOverloadsAreSkippedIfNonObsoleteOverloadIsAvailable()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M(int i) (+ย 1ย {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task FirstObsoleteOverloadIsUsedIfAllOverloadsAreObsolete()
{
var markup =
@"
public class C
{
[System.Obsolete]
public void M() { }
[System.Obsolete]
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"[{CSharpFeaturesResources.deprecated}] void C.M() (+ย 1ย {FeaturesResources.overload})");
}
[WorkItem(49609, "https://github.com/dotnet/roslyn/issues/49609")]
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task IgnoreCustomObsoleteAttribute()
{
var markup =
@"
public class ObsoleteAttribute: System.Attribute
{
}
public class C
{
[Obsolete]
public void M() { }
public void M(int i) { }
public void Test()
{
this.$$
}
}
";
await VerifyItemExistsAsync(markup, "M", expectedDescriptionOrNull: $"void C.M() (+ย 1ย {FeaturesResources.overload})");
}
[InlineData("int", "")]
[InlineData("int[]", "int a")]
[Theory, Trait(Traits.Feature, Traits.Features.TargetTypedCompletion)]
public async Task TestTargetTypeCompletionDescription(string targetType, string expectedParameterList)
{
// Check the description displayed is based on symbol matches targeted type
SetExperimentOption(WellKnownExperimentNames.TargetTypedCompletionFilter, true);
var markup =
$@"public class C
{{
bool Bar(int a, int b) => false;
int Bar() => 0;
int[] Bar(int a) => null;
bool N({targetType} x) => true;
void M(C c)
{{
N(c.$$);
}}
}}";
await VerifyItemExistsAsync(
markup, "Bar",
expectedDescriptionOrNull: $"{targetType} C.Bar({expectedParameterList}) (+{NonBreakingSpaceString}2{NonBreakingSpaceString}{FeaturesResources.overloads_})",
matchingFilters: new List<CompletionFilter> { FilterSet.MethodFilter, FilterSet.TargetTypedFilter });
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesNotSuggestedInDeclarationDeconstruction()
{
await VerifyItemIsAbsentAsync(@"
class C
{
int M()
{
var (x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestTypesSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
(x, $$) = (0, 0);
}
}", "C");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestLocalDeclaredBeforeDeconstructionSuggestedInMixedDeclarationAndAssignmentInDeconstruction()
{
await VerifyItemExistsAsync(@"
class C
{
int M()
{
int y;
(var x, $$) = (0, 0);
}
}", "y");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[WorkItem(53930, "https://github.com/dotnet/roslyn/issues/53930")]
public async Task TestTypeParameterConstraintedToInterfaceWithStatics()
{
var source = @"
interface I1
{
static void M0();
static abstract void M1();
abstract static int P1 { get; set; }
abstract static event System.Action E1;
}
interface I2
{
static abstract void M2();
}
class Test
{
void M<T>(T x) where T : I1, I2
{
T.$$
}
}
";
await VerifyItemIsAbsentAsync(source, "M0");
await VerifyItemExistsAsync(source, "M1");
await VerifyItemExistsAsync(source, "M2");
await VerifyItemExistsAsync(source, "P1");
await VerifyItemExistsAsync(source, "E1");
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Formatting/FormattingEngineTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class FormattingEngineTests : CSharpFormattingEngineTestBase
{
public FormattingEngineTests(ITestOutputHelper output) : base(output) { }
private static Dictionary<OptionKey2, object> SmartIndentButDoNotFormatWhileTyping()
{
return new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart },
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false },
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false },
};
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithView(expected, code);
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentPasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true);
}
[WpfFact]
[WorkItem(547261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentReadOnlyWorkspacePasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatUsingStatementWhenTypingCloseParen()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)
}
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatNotUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WorkItem(977133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine()
{
var code = @"class C
{
public void M()
{
if (true) {$$
}
}";
var expected = @"class C
{
public void M()
{
if (true) {
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(14491, "https://github.com/dotnet/roslyn/pull/14491")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine()
{
var code = @"class C
{
public void M()
{
if (true)
{$$
}
}";
var expected = @"class C
{
public void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(1007071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatPragmaWarningInbetweenDelegateDeclarationStatement()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
Func <bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
Func<bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashEndRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansIndividuallyWithoutCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
if(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if(true){}
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansWithCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
while(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
while (true) { }
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true)));
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(1044118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SemicolonInCommentOnLastLineDoesNotFormat()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;$$";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_1()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_2()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_1()
{
var code = @"class Program
{
static void Main(int a/* {$$ */, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* { */, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_2()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_3()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_1()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_2()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_1()
{
var code = @"class Program
{
/** {$$ **/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** { **/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_2()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_3()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideInactiveCode()
{
var code = @"class Program
{
#if false
{$$
#endif
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#if false
{
#endif
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideStringLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{$$"" ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{"" ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCharLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = '{$$' ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = '{' ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCommentsOfPreprocessorDirectives()
{
var code = @"class Program
{
#region
#endregion // a/*{$$*/
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#region
#endregion // a/*{*/
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1 :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInDefaultSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(9097, "https://github.com/dotnet/roslyn/issues/9097")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInPatternSwitchCase01()
{
var code = @"class Program
{
static void Main()
{
switch(f)
{
case int i :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main()
{
switch(f)
{
case int i: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInLabeledStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
label1 :$$ int s = 0;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
label1: int s = 0;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTargetAttribute()
{
var code = @"using System;
[method :$$ C]
class C : Attribute
{
}";
var expected = @"using System;
[method : C]
class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInBaseList()
{
var code = @"class C :$$ Attribute
{
}";
var expected = @"class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInThisConstructor()
{
var code = @"class Goo
{
Goo(int s) :$$ this()
{
}
Goo()
{
}
}";
var expected = @"class Goo
{
Goo(int s) : this()
{
}
Goo()
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInConditionalOperator()
{
var code = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true :$$ false;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true : false;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInArgument()
{
var code = @"class Program
{
static void Main(string[] args)
{
Main(args :$$ args);
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
Main(args : args);
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTypeParameter()
{
var code = @"class Program<T>
{
class C1<U>
where T :$$ U
{
}
}";
var expected = @"class Program<T>
{
class C1<U>
where T : U
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DontSmartFormatBracesOnSmartIndentNone()
{
var code = @"class Program<T>
{
class C1<U>
{$$
}";
var expected = @"class Program<T>
{
class C1<U>
{
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoIndentCloseBraceWhenFormatOnTypingIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void KeepTabsInCommentsWhenFormattingIsOff()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotKeepTabsInCommentsWhenFormattingIsOn()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code = @"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfSemicolonOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfTypingOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyNotFormattedIfNotAtStartOfLine()
{
var code =
@"
class C
{
public int P {$$
}
";
var expected =
@"
class C
{
public int P {
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyFormattedIfAtStartOfLine()
{
var code =
@"
class C
{
public int P
{$$
}
";
var expected =
@"
class C
{
public int P
{
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}$$";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;$$
x.ToString();
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}$$
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch
{
return;
x.ToString();
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(11642, "https://github.com/dotnet/roslyn/issues/11642")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatArbitraryNodeParenthesizedLambdaExpression()
{
// code equivalent to an expression synthesized like so:
// ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block()))
var code = @"(()=>{})";
var node = SyntaxFactory.ParseExpression(code);
var expected = @"(() => { })";
AssertFormatOnArbitraryNode(node, expected);
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2()
{
var code =
@"class Program
{
void M()
{
if (true)
{}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true )
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true )
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true ){$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true ){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7()
{
var code =
@"class Program
{
void M()
{$$
}";
var expected =
@"class Program
{
void M()
{
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2()
{
// Note that the { is not updated since we are not formatting.
var code =
@"class Program
{
void M()
{
if (true) {
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true) {
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3()
{
var code =
@"class Program
{
void M()
{
}$$
}";
var expected =
@"class Program
{
void M()
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4()
{
// Should not affect formatting of open brace
var code =
@"class Program
{
void M() {
}$$
}";
var expected =
@"class Program
{
void M() {
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(31907, "https://github.com/dotnet/roslyn/issues/31907")]
public async Task NullableReferenceTypes()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType;
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType;
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(30518, "https://github.com/dotnet/roslyn/issues/30518")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatGeneratedNodeInInitializer()
{
var code = @"new bool[] {
true,
true
}";
var expected = @"new bool[] {
true,
true == false, true
}";
var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script);
var root = tree.GetRoot();
var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));
var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), new[] { entry });
AssertFormatOnArbitraryNode(newRoot, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(27268, "https://github.com/dotnet/roslyn/issues/27268")]
public async Task PositionalPattern()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var point = new Point (3, 4);
if (point is Point (3, 4) _
&& point is Point{x: 3, y: 4} _)
{
}
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var point = new Point(3, 4);
if (point is Point(3, 4) _
&& point is Point { x: 3, y: 4 } _)
{
}
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression()
{
var code = @"[|
record C(int Property)
{
void M()
{
_ = this with { Property = 1 } ;
}
}
|]";
var expected = @"
record C(int Property)
{
void M()
{
_ = this with { Property = 1 };
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine_UserPositionedBraces()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_DoNotGroupIfNotSorted()
{
var code = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
var expected = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst()
{
var code = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
var expected = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")]
public void PreserveAnnotationsOnMultiLineTrivia()
{
var text = @"
namespace TestApp
{
class Test
{
/* __marker__ */
}
}
";
var position = text.IndexOf("/* __marker__ */");
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var root = syntaxTree.GetRoot();
var annotation = new SyntaxAnnotation("marker");
var markerTrivia = root.FindTrivia(position, findInsideTrivia: true);
var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation);
root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia);
var formattedRoot = Formatter.Format(root, new AdhocWorkspace());
var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker");
Assert.Single(annotatedTrivia);
}
private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary<OptionKey2, object> changedOptionSet = null)
{
using var workspace = TestWorkspace.CreateCSharp(code);
if (changedOptionSet != null)
{
var options = workspace.Options;
foreach (var entry in changedOptionSet)
{
options = options.WithChangedOption(entry.Key, entry.Value);
}
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));
}
var subjectDocument = workspace.Documents.Single();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1);
commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create());
var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
Assert.Equal(expected, newSnapshot.GetText());
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.BraceCompletion;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor.Implementation.Formatting;
using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Formatting
{
public class FormattingEngineTests : CSharpFormattingEngineTestBase
{
public FormattingEngineTests(ITestOutputHelper output) : base(output) { }
private static Dictionary<OptionKey2, object> SmartIndentButDoNotFormatWhileTyping()
{
return new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.Smart },
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false },
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false },
};
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithView(expected, code);
}
[WpfFact]
[WorkItem(539682, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539682")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentPasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true);
}
[WpfFact]
[WorkItem(547261, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547261")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatDocumentReadOnlyWorkspacePasteCommandHandler()
{
var code = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
int x;$$
int y;
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatUsingStatementWhenTypingCloseParen()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
using (null)
}
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[WorkItem(912965, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/912965")]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatNotUsingStatementOnReturn()
{
var code = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
var expected = @"class Program
{
static void Main(string[] args)
{
using (null)
for (;;)$$
}
}
";
AssertFormatWithPasteOrReturn(expected, code, allowDocumentChanges: true, isPaste: false);
}
[WorkItem(977133, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/977133")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeOrFormatTokenOnOpenBraceOnSameLine()
{
var code = @"class C
{
public void M()
{
if (true) {$$
}
}";
var expected = @"class C
{
public void M()
{
if (true) {
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(14491, "https://github.com/dotnet/roslyn/pull/14491")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatRangeButFormatTokenOnOpenBraceOnNextLine()
{
var code = @"class C
{
public void M()
{
if (true)
{$$
}
}";
var expected = @"class C
{
public void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(1007071, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1007071")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatPragmaWarningInbetweenDelegateDeclarationStatement()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
Func <bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
Func<bool> a = delegate ()
#pragma warning disable CA0001
{
return true;
};
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(771761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/771761")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatHashEndRegion()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion$$
}
}";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
#region
#endregion
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansIndividuallyWithoutCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
if(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if(true){}
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(987373, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/987373")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task FormatSpansWithCollapsing()
{
var code = @"class C
{
public void M()
{
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
[|if(true){}|]
while(true){}
[|if(true){}|]
}
}";
var expected = @"class C
{
public void M()
{
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
if (true) { }
while (true) { }
if (true) { }
}
}";
using var workspace = TestWorkspace.CreateCSharp(code);
var subjectDocument = workspace.Documents.Single();
var spans = subjectDocument.SelectedSpans;
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(workspace.Options
.WithChangedOption(FormattingOptions2.AllowDisjointSpanMerging, true)));
var document = workspace.CurrentSolution.Projects.Single().Documents.Single();
var syntaxRoot = await document.GetSyntaxRootAsync();
var node = Formatter.Format(syntaxRoot, spans, workspace);
Assert.Equal(expected, node.ToFullString());
}
[WorkItem(1044118, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1044118")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SemicolonInCommentOnLastLineDoesNotFormat()
{
var code = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;$$";
var expected = @"using System;
class Program
{
static void Main(string[] args)
{
}
}
// ;";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_1()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineRegularComment_2()
{
var code = @"class Program
{
// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_1()
{
var code = @"class Program
{
static void Main(int a/* {$$ */, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* { */, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_2()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineRegularComment_3()
{
var code = @"class Program
{
static void Main(int a/* {$$
*/, int b)
{
}
}";
var expected = @"class Program
{
static void Main(int a/* {
*/, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_1()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideSingleLineDocComment_2()
{
var code = @"class Program
{
/// {$$
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/// {
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_1()
{
var code = @"class Program
{
/** {$$ **/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** { **/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_2()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideMultiLineDocComment_3()
{
var code = @"class Program
{
/** {$$
**/
static void Main(int a, int b)
{
}
}";
var expected = @"class Program
{
/** {
**/
static void Main(int a, int b)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideInactiveCode()
{
var code = @"class Program
{
#if false
{$$
#endif
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#if false
{
#endif
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideStringLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{$$"" ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = ""{"" ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCharLiteral()
{
var code = @"class Program
{
static void Main(string[] args)
{
var asdas = '{$$' ;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var asdas = '{' ;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(449, "https://github.com/dotnet/roslyn/issues/449")]
[WorkItem(1077103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1077103")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void NoFormattingInsideCommentsOfPreprocessorDirectives()
{
var code = @"class Program
{
#region
#endregion // a/*{$$*/
static void Main(string[] args)
{
}
}";
var expected = @"class Program
{
#region
#endregion // a/*{*/
static void Main(string[] args)
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1 :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInDefaultSwitchCase()
{
var code = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
int f = 0;
switch(f)
{
case 1: break;
default: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(9097, "https://github.com/dotnet/roslyn/issues/9097")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInPatternSwitchCase01()
{
var code = @"class Program
{
static void Main()
{
switch(f)
{
case int i :$$ break;
}
}
}";
var expected = @"class Program
{
static void Main()
{
switch(f)
{
case int i: break;
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void ColonInLabeledStatement()
{
var code = @"class Program
{
static void Main(string[] args)
{
label1 :$$ int s = 0;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
label1: int s = 0;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTargetAttribute()
{
var code = @"using System;
[method :$$ C]
class C : Attribute
{
}";
var expected = @"using System;
[method : C]
class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInBaseList()
{
var code = @"class C :$$ Attribute
{
}";
var expected = @"class C : Attribute
{
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInThisConstructor()
{
var code = @"class Goo
{
Goo(int s) :$$ this()
{
}
Goo()
{
}
}";
var expected = @"class Goo
{
Goo(int s) : this()
{
}
Goo()
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInConditionalOperator()
{
var code = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true :$$ false;
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
var vari = goo() ? true : false;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInArgument()
{
var code = @"class Program
{
static void Main(string[] args)
{
Main(args :$$ args);
}
}";
var expected = @"class Program
{
static void Main(string[] args)
{
Main(args : args);
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(464, "https://github.com/dotnet/roslyn/issues/464")]
[WorkItem(908729, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/908729")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatColonInTypeParameter()
{
var code = @"class Program<T>
{
class C1<U>
where T :$$ U
{
}
}";
var expected = @"class Program<T>
{
class C1<U>
where T : U
{
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(2224, "https://github.com/dotnet/roslyn/issues/2224")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DontSmartFormatBracesOnSmartIndentNone()
{
var code = @"class Program<T>
{
class C1<U>
{$$
}";
var expected = @"class Program<T>
{
class C1<U>
{
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.SmartIndent, LanguageNames.CSharp), FormattingOptions.IndentStyle.None }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void StillAutoIndentCloseBraceWhenFormatOnCloseBraceIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(BraceCompletionOptions.AutoFormattingOnCloseBrace, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void AutoIndentCloseBraceWhenFormatOnTypingIsOff()
{
var code = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}$$
}
";
var expected = @"namespace N
{
class C
{
// improperly indented code
int x = 10;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void KeepTabsInCommentsWhenFormattingIsOff()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WorkItem(5873, "https://github.com/dotnet/roslyn/issues/5873")]
[WpfFact, Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotKeepTabsInCommentsWhenFormattingIsOn()
{
// There are tabs in this test case. Tools that touch the Roslyn repo should
// not remove these as we are explicitly testing tab behavior.
var code = @"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}$$
}";
var expected =
@"class Program
{
static void Main()
{
return; /* Comment preceded by tabs */ // This one too
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfSemicolonOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnSemicolon, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void DoNotFormatStatementIfTypingOptionIsOff()
{
var code =
@"namespace N
{
class C
{
int x = 10 ;$$
}
}
";
var expected =
@"namespace N
{
class C
{
int x = 10 ;
}
}
";
var optionSet = new Dictionary<OptionKey2, object>
{
{ new OptionKey2(FormattingOptions2.AutoFormattingOnTyping, LanguageNames.CSharp), false }
};
AssertFormatAfterTypeChar(code, expected, optionSet);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyNotFormattedIfNotAtStartOfLine()
{
var code =
@"
class C
{
public int P {$$
}
";
var expected =
@"
class C
{
public int P {
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, WorkItem(4435, "https://github.com/dotnet/roslyn/issues/4435")]
[Trait(Traits.Feature, Traits.Features.SmartTokenFormatting)]
public void OpenCurlyFormattedIfAtStartOfLine()
{
var code =
@"
class C
{
public int P
{$$
}
";
var expected =
@"
class C
{
public int P
{
}
";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatIncompleteBlockOnSingleLineIfNotTypingCloseCurly3()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;$$
}
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property { get { return true; }
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly1()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}$$
}";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatIncompleteBlockOnMultipleLinesIfTypingCloseCurly2()
{
var code = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get { return true;
}
}$$";
var expected = @"namespace ConsoleApplication1
{
class Program
{
static bool Property
{
get
{
return true;
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoNotFormatCompleteBlockOnSingleLineIfTypingSemicolon()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;$$
x.ToString();
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatCompleteBlockOnSingleLineIfTypingCloseCurlyOnLaterLine()
{
var code =
@"public class Class1
{
void M()
{
try { }
catch { return;
x.ToString();
}$$
}
}";
var expected =
@"public class Class1
{
void M()
{
try { }
catch
{
return;
x.ToString();
}
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonDifferentLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l)
Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(7900, "https://github.com/dotnet/roslyn/issues/7900")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatLockStatementWithEmbeddedStatementOnSemicolonSameLine()
{
var code = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");$$
}
}";
var expected = @"class C
{
private object _l = new object();
public void M()
{
lock (_l) Console.WriteLine(""d"");
}
}";
AssertFormatAfterTypeChar(code, expected);
}
[WorkItem(11642, "https://github.com/dotnet/roslyn/issues/11642")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatArbitraryNodeParenthesizedLambdaExpression()
{
// code equivalent to an expression synthesized like so:
// ParenthesizedExpression(ParenthesizedLambdaExpression(ParameterList(), Block()))
var code = @"(()=>{})";
var node = SyntaxFactory.ParseExpression(code);
var expected = @"(() => { })";
AssertFormatOnArbitraryNode(node, expected);
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff2()
{
var code =
@"class Program
{
void M()
{
if (true)
{}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff3()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff4()
{
// We only smart indent the { if it's on it's own line.
var code =
@"class Program
{
void M()
{
if (true){}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true){ }
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff5()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true )
{$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true )
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff6()
{
// Typing the { should not affect the formating of the preceding tokens.
var code =
@"class Program
{
void M()
{
if ( true ){$$
}
}";
var expected =
@"class Program
{
void M()
{
if ( true ){
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentOpenBraceEvenWithFormatWhileTypingOff7()
{
var code =
@"class Program
{
void M()
{$$
}";
var expected =
@"class Program
{
void M()
{
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff1()
{
var code =
@"class Program
{
void M()
{
if (true)
{
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true)
{
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff2()
{
// Note that the { is not updated since we are not formatting.
var code =
@"class Program
{
void M()
{
if (true) {
}$$
}
}";
var expected =
@"class Program
{
void M()
{
if (true) {
}
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff3()
{
var code =
@"class Program
{
void M()
{
}$$
}";
var expected =
@"class Program
{
void M()
{
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WorkItem(30787, "https://github.com/dotnet/roslyn/issues/30787")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void DoSmartIndentCloseBraceEvenWithFormatWhileTypingOff4()
{
// Should not affect formatting of open brace
var code =
@"class Program
{
void M() {
}$$
}";
var expected =
@"class Program
{
void M() {
}
}";
AssertFormatAfterTypeChar(code, expected, SmartIndentButDoNotFormatWhileTyping());
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(31907, "https://github.com/dotnet/roslyn/issues/31907")]
public async Task NullableReferenceTypes()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt !: method).ReturnType;
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var returnType = (_useMethodSignatureReturnType ? _methodSignatureOpt! : method).ReturnType;
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(30518, "https://github.com/dotnet/roslyn/issues/30518")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void FormatGeneratedNodeInInitializer()
{
var code = @"new bool[] {
true,
true
}";
var expected = @"new bool[] {
true,
true == false, true
}";
var tree = SyntaxFactory.ParseSyntaxTree(code, options: TestOptions.Script);
var root = tree.GetRoot();
var entry = SyntaxFactory.BinaryExpression(SyntaxKind.EqualsExpression, SyntaxFactory.LiteralExpression(SyntaxKind.TrueLiteralExpression), SyntaxFactory.LiteralExpression(SyntaxKind.FalseLiteralExpression));
var newRoot = root.InsertNodesBefore(root.DescendantNodes().Last(), new[] { entry });
AssertFormatOnArbitraryNode(newRoot, expected);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
[WorkItem(27268, "https://github.com/dotnet/roslyn/issues/27268")]
public async Task PositionalPattern()
{
var code = @"[|
class MyClass
{
void MyMethod()
{
var point = new Point (3, 4);
if (point is Point (3, 4) _
&& point is Point{x: 3, y: 4} _)
{
}
}
}
|]";
var expected = @"
class MyClass
{
void MyMethod()
{
var point = new Point(3, 4);
if (point is Point(3, 4) _
&& point is Point { x: 3, y: 4 } _)
{
}
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression()
{
var code = @"[|
record C(int Property)
{
void M()
{
_ = this with { Property = 1 } ;
}
}
|]";
var expected = @"
record C(int Property)
{
void M()
{
_ = this with { Property = 1 };
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WpfFact]
[Trait(Traits.Feature, Traits.Features.Formatting)]
public async Task WithExpression_MultiLine_UserPositionedBraces()
{
var code = @"[|
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
} ;
}
}
|]";
var expected = @"
record C(int Property, int Property2)
{
void M()
{
_ = this with
{
Property = 1,
Property2 = 2
};
}
}
";
await AssertFormatWithBaseIndentAsync(expected, code, baseIndentation: 4);
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_KeepMultipleLinesBetweenGroups_FileScopedNamespace()
{
var code = @"$$
namespace N;
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
namespace N;
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_DoNotGroupIfNotSorted()
{
var code = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
var expected = @"$$
using System.B;
using System.A;
using MS.B;
using MS.A;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted()
{
var code = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
var expected = @"$$
using System.A;
using System.B;
using MS.A;
using MS.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[WorkItem(25003, "https://github.com/dotnet/roslyn/issues/25003")]
[WpfFact, Trait(Traits.Feature, Traits.Features.Formatting)]
public void SeparateGroups_GroupIfSorted_RecognizeSystemNotFirst()
{
var code = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
var expected = @"$$
using MS.A;
using MS.B;
using System.A;
using System.B;
";
AssertFormatWithView(expected, code, (GenerationOptions.SeparateImportDirectiveGroups, true));
}
[Fact, WorkItem(49492, "https://github.com/dotnet/roslyn/issues/49492")]
public void PreserveAnnotationsOnMultiLineTrivia()
{
var text = @"
namespace TestApp
{
class Test
{
/* __marker__ */
}
}
";
var position = text.IndexOf("/* __marker__ */");
var syntaxTree = CSharpSyntaxTree.ParseText(text);
var root = syntaxTree.GetRoot();
var annotation = new SyntaxAnnotation("marker");
var markerTrivia = root.FindTrivia(position, findInsideTrivia: true);
var annotatedMarkerTrivia = markerTrivia.WithAdditionalAnnotations(annotation);
root = root.ReplaceTrivia(markerTrivia, annotatedMarkerTrivia);
var formattedRoot = Formatter.Format(root, new AdhocWorkspace());
var annotatedTrivia = formattedRoot.GetAnnotatedTrivia("marker");
Assert.Single(annotatedTrivia);
}
private static void AssertFormatAfterTypeChar(string code, string expected, Dictionary<OptionKey2, object> changedOptionSet = null)
{
using var workspace = TestWorkspace.CreateCSharp(code);
if (changedOptionSet != null)
{
var options = workspace.Options;
foreach (var entry in changedOptionSet)
{
options = options.WithChangedOption(entry.Key, entry.Value);
}
workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(options));
}
var subjectDocument = workspace.Documents.Single();
var commandHandler = workspace.GetService<FormatCommandHandler>();
var typedChar = subjectDocument.GetTextBuffer().CurrentSnapshot.GetText(subjectDocument.CursorPosition.Value - 1, 1);
commandHandler.ExecuteCommand(new TypeCharCommandArgs(subjectDocument.GetTextView(), subjectDocument.GetTextBuffer(), typedChar[0]), () => { }, TestCommandExecutionContext.Create());
var newSnapshot = subjectDocument.GetTextBuffer().CurrentSnapshot;
Assert.Equal(expected, newSnapshot.GetText());
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Test2/Rename/RenameEngineTests.CSharpConflicts.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Partial Public Class RenameEngineTests
<[UseExportProvider]>
Public Class CSharpConflicts
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<WpfTheory>
<WorkItem(773543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773543")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
class D { public int x = 1; }
Action<int> a = (int [|$$x|]) => // Rename x to y
{
var {|Conflict:y|} = new D();
Console.{|Conflict:WriteLine|}({|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773534")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct y
{
public int x;
}
class C
{
class D { public int x = 1; }
Action<y> a = (y [|$$x|]) => // Rename x to y
{ var {|Conflict:y|} = new D();
Console.WriteLine(y.x);
Console.WriteLine({|Conflict:x|}.{|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773435")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithInvocationOnDelegateInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public delegate void Foo(int x);
public void FooMeth(int x)
{
}
public void Sub()
{
Foo {|Conflict:x|} = new Foo(FooMeth);
int [|$$z|] = 1; // Rename z to x
int y = {|Conflict:z|};
x({|Conflict:z|}); // Renamed to x(x)
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(782020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782020")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithSameClassInOneNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using K = N.{|Conflict:C|}; // No change, show compiler error
namespace N
{
class {|Conflict:C|}
{
}
}
namespace N
{
class {|Conflict:$$D|} // Rename D to C
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameCrossAssembly(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class D
Public Sub Boo()
Dim x = New {|Conflict:$$C|}()
End Sub
End Class
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document>
public class [|C|]
{
public static void Foo()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideLambdaBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Proaasgram
{
object z;
public void masdain(string[] args)
{
Func<int, bool> sx = (int [|$$x|]) =>
{
{|resolve:z|} = null;
if (true)
{
bool y = foo([|x|]);
}
return true;
};
}
public bool foo(int bar)
{
return true;
}
public bool foo(object bar)
{
return true;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public static readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideMethodBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int Y(int [|$$y|])
{
[|y|] = 0;
return {|resolve:z|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_5(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code> z.Ex();</code>.Value + vbCrLf +
<code> x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|stmt2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|resolved:foo|} = 23;
{|resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @if;
void Blah(int {|Escape1:$$bar|})
{
{|Resolve:@if|} = 23;
{|Resolve2:@if|} = {|Escape2:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithStaticField(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
static int foo;
void Blah(int [|$$bar|])
{
{|Resolved:foo|} = 23;
{|Resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithFieldFromAnotherLanguage(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VisualBasicAssembly</ProjectReference>
<Document>
class Foo : FooBase
{
void Blah(int bar)
{
{|Resolve:$$foo|} = bar;
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true">
<Document>
Public Class FooBase
Protected [|foo|] As Integer
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539745")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingTypeDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="6">
<Document>< { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Goo")
result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="`")
result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host,
renameTo:="!")
result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<WorkItem(539636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539636")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void F()
{
}
class Blah
{
void [|$$M|]()
{
{|Replacement:F|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
int foo;
{|Replacement:Bar|}();
}
void [|$$Bar|]()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingTypeToConflictingMemberAndParentTypeName(host As RenameTestHost)
' It's important that we see conflicts for both simultaneously, so I do a single
' test for both cases.
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
class [|$$Bar|]
{
int {|Conflict:Foo|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToNameConflictingWithParent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
int [|$$Bar|];
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(540199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540199")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToInvalidIdentifierName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo@")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class [|$$A|] { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class B { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class A { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class [|$$B|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeIfKeywordWhenDoingTypeNameQualification(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class Foo
{
static void {|Escape:Method$$|}() { }
static void Test()
{
int @if;
{|Replacement:Method|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S> { }
}
class Program
{
static void Main()
{
var type = typeof({|stmt1:C|}.B<>);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|]
{
public class B<S>
{
public class E { }
}
}
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int[]>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int*>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithNestedGenericType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>.E;
class A<T>
{
public class E { }
}
class B
{
{|Resolve:C|} x;
class [|D$$|] { } // Rename D to C
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSite(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C Bar(int tag)
{
return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2);
}
}
static class E
{
public static C [|$$Foo|](this C x, int tag) { return new C(); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this, 1), 2);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(528902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528902")>
<WorkItem(645152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645152")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|$$Bar|](int tag)
{
this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2);
}
}
static class E
{
public static C Foo(this C x, int tag) { return x; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this, 1), 2);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542821")>
Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>()
{
{|Replacement:this.{|Resolved:Foo|}<int>()|};
}
}
static class E
{
public static void Foo<T>(this C x) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)")
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>(T y)
{
{|Replacement:this.{|Resolved:Foo|}(42)|};
}
}
static class E
{
public static void Foo<T>(this C x, T y) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DoNotDetectQueryContinuationNamedTheSame(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from {|stmt1:$$x|} in "abc"
select {|stmt1:x|} into y
select y;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
' This may feel strange, but the "into" effectively splits scopes
' into two. There are no errors here.
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesUsingWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
class Program
{
public static void Main(string[] args)
{
Stream {|stmt1:$$s|} = new Stream();
using ({|stmt2:s|})
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesForWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
public static void Main(string[] args)
{
int {|stmt1:$$i|};
for ({|stmt2:i|} = 0; ; )
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Special:Something|}()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="SpecialAttribute")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAddAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|Something|]()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameKeepAttributeSuffixOnUsages(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|SomethingAttribute|]()]
class Foo { }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameToConflictWithValue(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
public int TestProperty
{
set
{
int [|$$x|];
[|x|] = {|Conflict:value|};
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="value")
' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict)
' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543482")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeWithConflictingUse(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
[Main()]
static void test() { }
}
class MainAttribute : System.Attribute
{
static void Main() { }
}
class [|$$Main|] : System.Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<WorkItem(542649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542649")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeWithGlobalWhenConflicting(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class A { }
class B
{
{|Resolve:A|} x;
class [|$$C|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolDoesNotConflictWithNestedLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
{ int x; }
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolConflictWithLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
int x;
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(528738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528738")>
Public Sub RenameAliasToCatchConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using [|$$A|] = X.Something;
using {|Conflict:B|} = X.SomethingElse;
namespace X
{
class Something { }
class SomethingElse { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeToCreateConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Escape:Main|}]
class Some
{
}
class SpecialAttribute : Attribute
{
}
class [|$$Main|] : Attribute // Rename 'Main' to 'Special'
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUsingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using [|$$S|] = System.Collections;
[A]
class A : {|Resolve:Attribute|}
{
}
class B
{
[|S|].ArrayList a;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Attribute")
result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16809, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/16809")>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
Public Sub RenameInNestedClasses(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A
{
public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
<WorkItem(531433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531433")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAndEscapeContextualKeywordsInCSharp(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System.Linq;
class [|t$$o|] // Rename 'to' to 'from'
{
object q = from x in "" select new {|resolved:to|}();
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="from")
result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(522774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522774")>
Public Sub RenameCrefWithConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : {|Resolve:F|}.I
{
/// <summary>
/// This is a function <see cref="{|Resolve:F|}.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$K|]
{
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameClassContainingAlias(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using C = A<int,int>;
class A<T,U>
{
public class B<S>
{
}
}
class [|$$B|]
{
{|Resolve:C|}.B<int> cb;
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionWithOverloadConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Bar
{
void Foo(int x) { }
void [|Boo|](object x) { }
void Some()
{
Foo(1);
{|Resolve:$$Boo|}(1);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameActionWithFunctionConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class Program
{
static void doer(int x)
{
Console.WriteLine("Hey");
}
static void Main(string[] args)
{
Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer
{|stmt2:doer|}(3);
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="doer")
result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552522")>
Public Sub RenameFunctionNameToDelegateTypeConflict1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|Foo|]() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
{|Stmt2:$$Foo|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Del")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|$$Foo|]() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionNameToDelegateTypeConflict3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
delegate void Del(Del a);
static void [|Bar|](Del a) { }
class B
{
Del Boo = new Del({|decl1:Bar|});
void Foo()
{
Boo({|Stmt2:Bar|});
{|Stmt3:$$Bar|}(Boo);
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Boo")
result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void Foo(int i) { }
static void Foo(string s) { }
class B
{
delegate void Del(string s);
void [|$$Bar|](string s) { }
void Boo()
{
Del d = new Del({|stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameActionTypeConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class A
{
static Action<int> [|$$Baz|] = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
{|Stmt1:Baz|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameConflictAttribute1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
[{|escape:Bar|}]
class Bar : System.Attribute
{ }
class [|$$FooAttribute|] : System.Attribute
{ }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BarAttribute")
result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameConflictAttribute2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Resolve:B|}]
class [|$$BAttribute|] : Attribute
{
}
class AAttributeAttribute : Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="AAttribute")
result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(576573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576573")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug576573_ConflictAttributeWithNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace X
{
class BAttribute
: System.Attribute
{ }
namespace Y.[|$$Z|]
{
[{|Resolve:B|}]
class Foo { }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BAttribute")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(579602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579602")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug579602_RenameFunctionWithDynamicParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
class B
{
public void [|Boo|](int d) { } //Line 1
}
void Bar()
{
B b = new B();
dynamic d = 1.5f;
b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub IdentifyConflictsWithVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class [|$$vor|]
{
static void Main(string[] args)
{
{|conflict:var|} x = 23;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="v\u0061r")
result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(633180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633180")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(635622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635622")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandingDynamicAddsObjectCast(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar
static void Bar(dynamic x, Action y) { }
static void Main()
{
{|resolve:Bar|}(1, Console.WriteLine);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNamespaceConflictsAndResolves(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace N
{
class C
{
{|resolve:N|}.C x;
/// <see cref="{|resolve:N|}.C"/>
void Sub()
{ }
}
namespace [|$$K|] // Rename K to N
{
class C
{ }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUnnecessaryExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
namespace N
{
using K = {|stmt1:N|}.C;
class C
{
}
class [|$$D|] // Rename D to N
{
class C
{
[|D|] x;
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(768910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768910")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInCrefPreservesWhitespaceTrivia(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
<![CDATA[
public class A
{
public class B
{
public class C
{
}
/// <summary>
/// <see cref=" {|Resolve:D|}"/>
/// </summary>
public static void [|$$foo|]() // Rename foo to D
{
}
}
public class D
{
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void F<T>(Func<int, T> x) { }
static void [|$$B|](Func<int, int> x) { } // Rename Bar to Foo
static void Main()
{
{|stmt1:F|}(a => a);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(725934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/725934")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_This(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void TestMethod()
{
int x = 1;
Func<int> y = delegate { return {|stmt1:Foo|}(x); };
}
int Foo<T>(T x) { return 1; }
int [|$$Bar|](int x) { return 1; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_Nested(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public static void [|$$Foo|]<T>(T x) { }
public static void Bar(int x) { }
class D
{
void Bar<T>(T x) { }
void Bar(int x) { }
void sub()
{
{|stmt1:Foo|}(1);
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ReferenceType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
string one = "1";
{|stmt1:Foo|}(one);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
D<int> x = new D<int>();
{|stmt1:Foo|}(x);
}
}
class D<T>
{}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System.Linq.Expressions;
class C
{
public static int Foo<T>(T x) { return 1; }
public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; }
Expression<Func<int, int>> x = (y) => Foo(1);
public void sub()
{
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void [|$$Foo|]<S>(S x) { }
public void Bar(int[] x) { }
public void Sub()
{
var x = new int[] { 1, 2, 3 };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
var x = new int[,] { { 1, 2 }, { 2, 3 } };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Sub(int x) { }
public void Test()
{
Sub({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Test()
{
C c = new C({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_CalledOnObject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
C c = new C();
c.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel foodel = new FooDel({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void Foo<T, S>(T x, S y) { }
public void [|$$Bar|]<U, P>(U[] x, P y) { }
public void Sub()
{
int[] x;
{|stmt1:Foo|}(x, new C());
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(730781, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730781")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728653")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameGenericInvocationWithDynamicArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to F
public void sub()
{
dynamic x = 1;
{|stmt1:F|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(728646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728646")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandInvocationInStaticMemberAccess(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
}
}
class D
{
public void Sub()
{
C.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728628")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RecursiveTypeParameterExpansionFail(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
C<int> x = new C<int>();
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728575")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename to Zoo
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Zoo")
result.AssertLabeledSpansAre("cref1", "Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_GenericBase(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
}
class D : C<int>
{
public void Test()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WpfTheory(Skip:="Story 736967"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_InErrorCode(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< // Rename Bar to Foo
{
x = 1;
}
public void Test()
{
int y = 1;
int x;
{|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T>
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#End Region
<WorkItem(1016652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016652")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
// rename INamespaceSymbol to ISymbol
public interface {|unresolved1:$$INamespaceSymbol|} { }
public interface {|DeclConflict:ISymbol|} { }
public interface IReferenceFinder { }
internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder
where TSymbol : {|unresolved2:INamespaceSymbol|}
{
}]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="ISymbol")
result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
static void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
static int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
int zoo;
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
void nameof(int x) { }
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInLambdaBodyExpression(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => 5;
static int N(long b) => 5;
System.Func<int, int> a = d => {|resolved:N|}(1);
System.Func<int> b = () => {|resolved:N|}(1);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInExpressionBodiedMembers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => {|resolved2:N|}(0);
int N(long b) => [|M|](0);
int P => {|resolved2:N|}(0);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
interface [|$$I|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class [|$$C|] { }
interface {|conflict:I|} { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="I")
result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
namespace [|$$N|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictBetweenTwoNamespaces(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
namespace [|$$N1|][ { }
namespace N2 { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M1(Action [|callback$$|])
{
[|callback|]();
}
void M2(Func<bool> callback)
{
callback();
}
void M3()
{
Action callback = () => { };
callback();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="callback2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M()
{
int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a.
Action {|conflict:a|} = () => { };
{|conflict:a|}();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static void [|T|]$$(int x) { }
[System.Obsolete(nameof(Test))]
static void Test() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Test()
{
int [|T$$|];
var x = nameof({|conflict:Test|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|$$M|](int x) { }
void M() { var x = nameof(M); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|X$$|]() { }
void M() { var x = nameof(T); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
static void M()
{
var [|Consol$$|] = 7;
var x = nameof({|conflict:Console|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Console")
result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C.D")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode(host As RenameTestHost)
Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }"
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:=renameTo)
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_SameProject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
internal void [|A$$|]() { }
internal void {|conflict:B|}() { }
}
</Document>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document FilePath="Test1.cs">
public class Program
{
public void [|A$$|]() { }
public void {|conflict:B|}() { }
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2">
<ProjectReference>CSAssembly1</ProjectReference>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
partial class C
{
private static void [|$$M|]()
{
{|conflict:M|}();
}
}
</Document>
<Document FilePath="Test2.cs">
partial class C
{
private static void {|conflict:Method|}()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Method")
result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
Program.nameof({|Conflict:field|}); // Should also expand to Program.field
}
static void nameof(string s) { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameTypeParameterInPartialClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<[|$$T|]> {}
partial class C<[|T|]> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T2")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameMethodToConflictWithTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<{|Conflict:T|}> { void [|$$M|]() { } }
partial class C<{|Conflict:T|}> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(10469, "https://github.com/dotnet/roslyn/issues/10469")>
Public Sub RenameTypeToCurrent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class {|current:$$C|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Current")
result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16567, "https://github.com/dotnet/roslyn/issues/16567")>
Public Sub RenameMethodToFinalizeWithDestructorPresent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
~{|Conflict:C|}() { }
void $$[|M|]()
{
int x = 7;
int y = ~x;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Finalize")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(5872, "https://github.com/dotnet/roslyn/issues/5872")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CannotRenameToVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class $${|Conflict:X|} {
{|Conflict:X|}() {
var a = 2;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="var")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertySetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:set|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyInitterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:init|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyGetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { {|conflict:get|}; set; }
private int {|conflict:$$_get_MyProperty|}() => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="get_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.Rename.ConflictEngine
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.Rename
Partial Public Class RenameEngineTests
<[UseExportProvider]>
Public Class CSharpConflicts
Private ReadOnly _outputHelper As Abstractions.ITestOutputHelper
Public Sub New(outputHelper As Abstractions.ITestOutputHelper)
_outputHelper = outputHelper
End Sub
<WpfTheory>
<WorkItem(773543, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773543")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class C
{
class D { public int x = 1; }
Action<int> a = (int [|$$x|]) => // Rename x to y
{
var {|Conflict:y|} = new D();
Console.{|Conflict:WriteLine|}({|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773534, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773534")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithRollBacksInsideLambdas_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
struct y
{
public int x;
}
class C
{
class D { public int x = 1; }
Action<y> a = (y [|$$x|]) => // Rename x to y
{ var {|Conflict:y|} = new D();
Console.WriteLine(y.x);
Console.WriteLine({|Conflict:x|}.{|Conflict:x|});
};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(773435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/773435")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithInvocationOnDelegateInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public delegate void Foo(int x);
public void FooMeth(int x)
{
}
public void Sub()
{
Foo {|Conflict:x|} = new Foo(FooMeth);
int [|$$z|] = 1; // Rename z to x
int y = {|Conflict:z|};
x({|Conflict:z|}); // Renamed to x(x)
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(782020, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/782020")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameWithSameClassInOneNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using K = N.{|Conflict:C|}; // No change, show compiler error
namespace N
{
class {|Conflict:C|}
{
}
}
namespace N
{
class {|Conflict:$$D|} // Rename D to C
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub BreakingRenameCrossAssembly(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="Visual Basic" CommonReferences="true" AssemblyName="VBAssembly1">
<ProjectReference>CSAssembly1</ProjectReference>
<Document>
Class D
Public Sub Boo()
Dim x = New {|Conflict:$$C|}()
End Sub
End Class
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document>
public class [|C|]
{
public static void Foo()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Conflict", "D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideLambdaBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Proaasgram
{
object z;
public void masdain(string[] args)
{
Func<int, bool> sx = (int [|$$x|]) =>
{
{|resolve:z|} = null;
if (true)
{
bool y = foo([|x|]);
}
return true;
};
}
public bool foo(int bar)
{
return true;
}
public bool foo(object bar)
{
return true;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "this.z = null;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + this.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + this.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(1069237, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1069237")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideExpressionBodiedLambda2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public static readonly int z = 0;
public int X(int [|$$x|]) => {|direct:x|} + {|resolve:z|};
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("direct", "z + B.z", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve", "z + B.z", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInsideMethodBody(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
using System.Collections.Generic;
using System.Linq;
public class B
{
public readonly int z = 0;
public int Y(int [|$$y|])
{
[|y|] = 0;
return {|resolve:z|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="z")
result.AssertLabeledSpansAre("resolve", "return this.z;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner(x => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:Ex|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="L")
Dim outputResult = <code>Outer((string y) => Inner((x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.L();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}((y) => {|resolve2:Inner|}((x) => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer((y) => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code>z.Ex();</code>.Value + vbCrLf +
<code>x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictResolutionInInvocationWithLambda_5(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolve1:Outer|}(y => {|resolve2:Inner|}(x => {
var z = 5;
z.{|resolve0:D|}();
x.Ex();
}, y), 0);
}
}
static class E
{
public static void [|$$D|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Ex")
Dim outputResult = <code>Outer(y => Inner((string x) => {</code>.Value + vbCrLf +
<code> var z = 5;</code>.Value + vbCrLf +
<code> z.Ex();</code>.Value + vbCrLf +
<code> x.Ex();</code>.Value + vbCrLf +
<code> }, y), 0);</code>.Value
result.AssertLabeledSpansAre("resolve0", outputResult, RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolve1", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolve2", outputResult, RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|stmt2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceField2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int foo;
void Blah(int [|$$bar|])
{
{|resolved:foo|} = 23;
{|resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("stmt1", "this.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("resolved", "this.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "this.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithInstanceFieldRenamingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
int @if;
void Blah(int {|Escape1:$$bar|})
{
{|Resolve:@if|} = 23;
{|Resolve2:@if|} = {|Escape2:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpansAre("Resolve", "this.@if = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpecialSpansAre("Escape1", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpecialSpansAre("Escape2", "this.@if = @if;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "this.@if = @if;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithStaticField(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Foo
{
static int foo;
void Blah(int [|$$bar|])
{
{|Resolved:foo|} = 23;
{|Resolved2:foo|} = {|stmt1:bar|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Resolved", "Foo.foo = 23;", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("stmt1", "Foo.foo = foo;", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolved2", "Foo.foo = foo;", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ParameterConflictingWithFieldFromAnotherLanguage(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<ProjectReference>VisualBasicAssembly</ProjectReference>
<Document>
class Foo : FooBase
{
void Blah(int bar)
{
{|Resolve:$$foo|} = bar;
}
}
</Document>
</Project>
<Project Language="Visual Basic" AssemblyName="VisualBasicAssembly" CommonReferences="true">
<Document>
Public Class FooBase
Protected [|foo|] As Integer
End Class
</Document>
</Project>
</Workspace>, host:=host, renameTo:="bar")
result.AssertLabeledSpansAre("Resolve", "base.bar = bar;", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539745, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539745")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictingTypeDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" LanguageVersion="6">
<Document>< { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Goo")
result.AssertLabeledSpansAre("ReplacementCInt", "C<int>.Goo(i, i);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("ReplacementCString", "C<string>.Goo(s, s);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="`")
result.AssertLabeledSpansAre("Invalid", "`", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToInvalidIdentifier2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
{|Invalid:Foo|} foo;
}
</Document>
</Project>
</Workspace>, host:=host,
renameTo:="!")
result.AssertLabeledSpansAre("Invalid", "!", RelatedLocationType.UnresolvedConflict)
result.AssertReplacementTextInvalid()
End Using
End Sub
<Theory>
<WorkItem(539636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539636")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static void F()
{
}
class Blah
{
void [|$$M|]()
{
{|Replacement:F|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Replacement", "Program.F();", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingToConflictingMethodInvocation2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void M()
{
int foo;
{|Replacement:Bar|}();
}
void [|$$Bar|]()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="foo")
result.AssertLabeledSpansAre("Replacement", "this.foo();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingTypeToConflictingMemberAndParentTypeName(host As RenameTestHost)
' It's important that we see conflicts for both simultaneously, so I do a single
' test for both cases.
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
class [|$$Bar|]
{
int {|Conflict:Foo|};
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(539733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539733")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToNameConflictingWithParent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Conflict:Foo|}
{
int [|$$Bar|];
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(540199, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540199")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenamingMemberToInvalidIdentifierName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|Invalid:$$Foo|}
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo@")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("Invalid", "Foo@", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class [|$$A|] { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class B { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MinimalQualificationOfBaseType2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class X
{
protected class A { }
}
class Y : X
{
private class C : {|Resolve:A|} { }
private class [|$$B|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "X.A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeIfKeywordWhenDoingTypeNameQualification(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
static class Foo
{
static void {|Escape:Method$$|}() { }
static void Test()
{
int @if;
{|Replacement:Method|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="if")
result.AssertLabeledSpecialSpansAre("Escape", "@if", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Replacement", "Foo.@if();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S> { }
}
class Program
{
static void Main()
{
var type = typeof({|stmt1:C|}.B<>);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("stmt1", "var type = typeof(A<>.B<>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542322, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542322")>
Public Sub EscapeUnboundGenericTypesInTypeOfContext3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>;
class A<T>
{
public class B<S>
{
public class E { }
}
}
class Program
{
static void Main()
{
var type = typeof({|Replacement:C|}.B<>.E);
}
class [|D$$|]
{
public class B<S>
{
public class E { }
}
}
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Replacement", "var type = typeof(A<>.B<>.E);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesArrays(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int[]>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int[]>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithGenericTypeThatIncludesPointers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int*>;
class A<T> { }
class Program
{
{|Resolve:C|} x;
class [|D$$|] { }
}
]]></Document>
</Project>
</Workspace>, host:=host,
renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int*>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542651, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542651")>
Public Sub ReplaceAliasWithNestedGenericType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using C = A<int>.E;
class A<T>
{
public class E { }
}
class B
{
{|Resolve:C|} x;
class [|D$$|] { } // Rename D to C
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int>.E", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSite(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
C Bar(int tag)
{
return this.{|stmt1:Foo|}(1).{|stmt1:Foo|}(2);
}
}
static class E
{
public static C [|$$Foo|](this C x, int tag) { return new C(); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "return E.Bar(E.Bar(this, 1), 2);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(528902, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528902")>
<WorkItem(645152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/645152")>
<WorkItem(8334, "https://github.com/dotnet/roslyn/issues/8334")>
Public Sub RewriteConflictingExtensionMethodCallSiteWithReturnTypeChange(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void [|$$Bar|](int tag)
{
this.{|Resolved:Foo|}(1).{|Resolved:Foo|}(2);
}
}
static class E
{
public static C Foo(this C x, int tag) { return x; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", "E.Foo(E.Foo(this, 1), 2);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542821, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542821")>
Public Sub RewriteConflictingExtensionMethodCallSiteRequiringTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>()
{
{|Replacement:this.{|Resolved:Foo|}<int>()|};
}
}
static class E
{
public static void Foo<T>(this C x) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo<int>(this)")
End Using
End Sub
<WpfTheory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(535068, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535068")>
<WorkItem(542103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542103")>
Public Sub RewriteConflictingExtensionMethodCallSiteInferredTypeArguments(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
class C
{
void [|$$Bar|]<T>(T y)
{
{|Replacement:this.{|Resolved:Foo|}(42)|};
}
}
static class E
{
public static void Foo<T>(this C x, T y) { }
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolved", type:=RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Replacement", "E.Foo(this, 42)")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DoNotDetectQueryContinuationNamedTheSame(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.Linq;
class C
{
static void Main(string[] args)
{
var temp = from {|stmt1:$$x|} in "abc"
select {|stmt1:x|} into y
select y;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="y")
' This may feel strange, but the "into" effectively splits scopes
' into two. There are no errors here.
result.AssertLabeledSpansAre("stmt1", "y", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesUsingWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System.IO;
class Program
{
public static void Main(string[] args)
{
Stream {|stmt1:$$s|} = new Stream();
using ({|stmt2:s|})
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(543027, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543027")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameHandlesForWithoutDeclaration(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
public static void Main(string[] args)
{
int {|stmt1:$$i|};
for ({|stmt2:i|} = 0; ; )
{
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("stmt1", "x", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "x", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Special:Something|}()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="SpecialAttribute")
result.AssertLabeledSpansAre("Special", "Special", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAddAttributeSuffix(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|Something|]()]
class Foo{ }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameKeepAttributeSuffixOnUsages(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[[|SomethingAttribute|]()]
class Foo { }
public class [|$$SomethingAttribute|] : Attribute
{
public [|SomethingAttribute|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameToConflictWithValue(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
public int TestProperty
{
set
{
int [|$$x|];
[|x|] = {|Conflict:value|};
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="value")
' result.AssertLabeledSpansAre("stmt1", "value", RelatedLocationType.NoConflict)
' result.AssertLabeledSpansAre("stmt2", "value", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<WorkItem(543482, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543482")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeWithConflictingUse(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class C
{
[Main()]
static void test() { }
}
class MainAttribute : System.Attribute
{
static void Main() { }
}
class [|$$Main|] : System.Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="FooAttribute")
End Using
End Sub
<Theory>
<WorkItem(542649, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542649")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub QualifyTypeWithGlobalWhenConflicting(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class A { }
class B
{
{|Resolve:A|} x;
class [|$$C|] { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve", "global::A", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
End Class
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolDoesNotConflictWithNestedLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
{ int x; }
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameSymbolConflictWithLocals(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void Foo()
{
int x;
{|Stmt1:Bar|}();
}
void [|$$Bar|]() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="x")
result.AssertLabeledSpansAre("Stmt1", "this.x();", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(528738, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528738")>
Public Sub RenameAliasToCatchConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using [|$$A|] = X.Something;
using {|Conflict:B|} = X.SomethingElse;
namespace X
{
class Something { }
class SomethingElse { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("Conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAttributeToCreateConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Escape:Main|}]
class Some
{
}
class SpecialAttribute : Attribute
{
}
class [|$$Main|] : Attribute // Rename 'Main' to 'Special'
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Special")
result.AssertLabeledSpecialSpansAre("Escape", "@Special", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUsingToKeyword(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using [|$$S|] = System.Collections;
[A]
class A : {|Resolve:Attribute|}
{
}
class B
{
[|S|].ArrayList a;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Attribute")
result.AssertLabeledSpansAre("Resolve", "System.Attribute", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16809, "http://vstfdevdiv:8080/DevDiv_Projects/Roslyn/_workitems/edit/16809")>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
Public Sub RenameInNestedClasses(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
namespace N
{
class A<T>
{
public virtual void Foo(T x) { }
class B<S> : A<B<S>>
{
class [|$$C|]<U> : B<{|Resolve1:C|}<U>> // Rename C to A
{
public override void Foo({|Resolve2:A|}<{|Resolve3:A|}<T>.B<S>>.B<{|Resolve4:A|}<T>.B<S>.{|Resolve1:C|}<U>> x) { }
}
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="A")
result.AssertLabeledSpansAre("Resolve1", "A", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("Resolve2", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve3", "N.A<N.A<T>.B<S>>", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("Resolve4", "N.A<T>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory()>
<WorkItem(535066, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/535066")>
<WorkItem(531433, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531433")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameAndEscapeContextualKeywordsInCSharp(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System.Linq;
class [|t$$o|] // Rename 'to' to 'from'
{
object q = from x in "" select new {|resolved:to|}();
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="from")
result.AssertLabeledSpansAre("resolved", "@from", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(522774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/522774")>
Public Sub RenameCrefWithConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using F = N;
namespace N
{
interface I
{
void Foo();
}
}
class C
{
class E : {|Resolve:F|}.I
{
/// <summary>
/// This is a function <see cref="{|Resolve:F|}.I.Foo"/>
/// </summary>
public void Foo() { }
}
class [|$$K|]
{
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("Resolve", "N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameClassContainingAlias(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
using C = A<int,int>;
class A<T,U>
{
public class B<S>
{
}
}
class [|$$B|]
{
{|Resolve:C|}.B<int> cb;
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("Resolve", "A<int, int>", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionWithOverloadConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
class Bar
{
void Foo(int x) { }
void [|Boo|](object x) { }
void Some()
{
Foo(1);
{|Resolve:$$Boo|}(1);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("Resolve", "Foo((object)1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameActionWithFunctionConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class Program
{
static void doer(int x)
{
Console.WriteLine("Hey");
}
static void Main(string[] args)
{
Action<int> {|stmt1:$$action|} = delegate(int x) { Console.WriteLine(x); }; // Rename action to doer
{|stmt2:doer|}(3);
}
}
]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="doer")
result.AssertLabeledSpansAre("stmt1", "doer", RelatedLocationType.NoConflict)
result.AssertLabeledSpansAre("stmt2", "Program.doer(3);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552522, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552522")>
Public Sub RenameFunctionNameToDelegateTypeConflict1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|Foo|]() { }
class B
{
delegate void Del();
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
{|Stmt2:$$Foo|}();
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Del")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Del);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Del", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void [|$$Foo|]() { }
class B
{
delegate void Del();
void Bar() { }
void Boo()
{
Del d = new Del({|Stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "Del d = new Del(A.Bar);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameFunctionNameToDelegateTypeConflict3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
delegate void Del(Del a);
static void [|Bar|](Del a) { }
class B
{
Del Boo = new Del({|decl1:Bar|});
void Foo()
{
Boo({|Stmt2:Bar|});
{|Stmt3:$$Bar|}(Boo);
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Boo")
result.AssertLabeledSpansAre("decl1", "new Del(A.Boo)", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt2", "Boo(A.Boo);", RelatedLocationType.ResolvedReferenceConflict)
result.AssertLabeledSpansAre("Stmt3", "A.Boo(Boo);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552520, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552520")>
Public Sub RenameFunctionNameToDelegateTypeConflict4(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
static void Foo(int i) { }
static void Foo(string s) { }
class B
{
delegate void Del(string s);
void [|$$Bar|](string s) { }
void Boo()
{
Del d = new Del({|stmt1:Foo|});
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Del d = new Del(A.Foo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameActionTypeConflict(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class A
{
static Action<int> [|$$Baz|] = (int x) => { };
class B
{
Action<int> Bar = (int x) => { };
void Foo()
{
{|Stmt1:Baz|}(3);
}
}
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("Stmt1", "A.Bar(3);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(552722, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/552722")>
Public Sub RenameConflictAttribute1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
[{|escape:Bar|}]
class Bar : System.Attribute
{ }
class [|$$FooAttribute|] : System.Attribute
{ }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BarAttribute")
result.AssertLabeledSpansAre("escape", "@Bar", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameConflictAttribute2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
[{|Resolve:B|}]
class [|$$BAttribute|] : Attribute
{
}
class AAttributeAttribute : Attribute
{
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="AAttribute")
result.AssertLabeledSpecialSpansAre("Resolve", "A", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(576573, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/576573")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug576573_ConflictAttributeWithNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace X
{
class BAttribute
: System.Attribute
{ }
namespace Y.[|$$Z|]
{
[{|Resolve:B|}]
class Foo { }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="BAttribute")
result.AssertLabeledSpansAre("Resolve", "X.B", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(579602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/579602")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub Bug579602_RenameFunctionWithDynamicParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class A
{
class B
{
public void [|Boo|](int d) { } //Line 1
}
void Bar()
{
B b = new B();
dynamic d = 1.5f;
b.{|stmt1:$$Boo|}(d); //Line 2 Rename Boo to Foo
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo", RelatedLocationType.NoConflict)
End Using
End Sub
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub IdentifyConflictsWithVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class [|$$vor|]
{
static void Main(string[] args)
{
{|conflict:var|} x = 23;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="v\u0061r")
result.AssertLabeledSpansAre("conflict", "var", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(633180, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/633180")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_DetectOverLoadResolutionChangesInEnclosingInvocations(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
static class C
{
static void Ex(this string x) { }
static void Outer(Action<string> x, object y) { Console.WriteLine(1); }
static void Outer(Action<int> x, int y) { Console.WriteLine(2); }
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 Main()
{
{|resolved:Outer|}(y => {|resolved:Inner|}(x => x.Ex(), y), 0);
}
}
static class E
{
public static void [|$$Ex|](this int x) { } // Rename Ex to Foo
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("resolved", "Outer((string y) => Inner(x => x.Ex(), y), 0);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(635622, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/635622")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandingDynamicAddsObjectCast(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void [|$$Foo|](int x, Action y) { } // Rename Foo to Bar
static void Bar(dynamic x, Action y) { }
static void Main()
{
{|resolve:Bar|}(1, Console.WriteLine);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("resolve", "Bar((object)1, Console.WriteLine);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673562, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673562")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameNamespaceConflictsAndResolves(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
namespace N
{
class C
{
{|resolve:N|}.C x;
/// <see cref="{|resolve:N|}.C"/>
void Sub()
{ }
}
namespace [|$$K|] // Rename K to N
{
class C
{ }
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolve", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(673667, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/673667")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameUnnecessaryExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
namespace N
{
using K = {|stmt1:N|}.C;
class C
{
}
class [|$$D|] // Rename D to N
{
class C
{
[|D|] x;
}
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("stmt1", "global::N", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(768910, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/768910")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInCrefPreservesWhitespaceTrivia(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
<![CDATA[
public class A
{
public class B
{
public class C
{
}
/// <summary>
/// <see cref=" {|Resolve:D|}"/>
/// </summary>
public static void [|$$foo|]() // Rename foo to D
{
}
}
public class D
{
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="D")
result.AssertLabeledSpansAre("Resolve", "A.D", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#Region "Type Argument Expand/Reduce for Generic Method Calls - 639136"
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
static void F<T>(Func<int, T> x) { }
static void [|$$B|](Func<int, int> x) { } // Rename Bar to Foo
static void Main()
{
{|stmt1:F|}(a => a);
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F<int>(a => a);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(725934, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/725934")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_This(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">
using System;
class C
{
void TestMethod()
{
int x = 1;
Func<int> y = delegate { return {|stmt1:Foo|}(x); };
}
int Foo<T>(T x) { return 1; }
int [|$$Bar|](int x) { return 1; }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "return Foo<int>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_Nested(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public static void [|$$Foo|]<T>(T x) { }
public static void Bar(int x) { }
class D
{
void Bar<T>(T x) { }
void Bar(int x) { }
void sub()
{
{|stmt1:Foo|}(1);
}
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "C.Bar<int>(1);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory(), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ReferenceType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
string one = "1";
{|stmt1:Foo|}(one);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<string>(one);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConstructedTypeArgumentNonGenericContainer(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
D<int> x = new D<int>();
{|stmt1:Foo|}(x);
}
}
class D<T>
{}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<D<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_SameTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System.Linq.Expressions;
class C
{
public static int Foo<T>(T x) { return 1; }
public static int [|$$Bar|]<T>(Expression<Func<int, T>> x) { return 1; }
Expression<Func<int, int>> x = (y) => Foo(1);
public void sub()
{
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<Expression<Func<int, int>>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void [|$$Foo|]<S>(S x) { }
public void Bar(int[] x) { }
public void Sub()
{
var x = new int[] { 1, 2, 3 };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Bar")
result.AssertLabeledSpansAre("stmt1", "Bar<int[]>(x);", RelatedLocationType.ResolvedReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultiDArrayTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
var x = new int[,] { { 1, 2 }, { 2, 3 } };
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[,]>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedAsArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Sub(int x) { }
public void Test()
{
Sub({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Sub(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInConstructorInitialization(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; }
public void Test()
{
C c = new C({|stmt1:Foo|}(1));
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C c = new C(Foo<int>(1));", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_CalledOnObject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
C c = new C();
c.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "c.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel<int> foodel = new FooDel<int>({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel<int> foodel = new FooDel<int>(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_UsedInNonGenericDelegate(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< {return 1; } // Rename Bar to Foo
public void Test()
{
FooDel foodel = new FooDel({|stmt1:Foo|});
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "FooDel foodel = new FooDel(Foo<int>);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_MultipleTypeParameters(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
public void Foo<T, S>(T x, S y) { }
public void [|$$Bar|]<U, P>(U[] x, P y) { }
public void Sub()
{
int[] x;
{|stmt1:Foo|}(x, new C());
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int[], C>(x, new C());", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WorkItem(730781, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/730781")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_ConflictInDerived(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { }
public void Sub()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "base.Foo(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728653")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameGenericInvocationWithDynamicArgument(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to F
public void sub()
{
dynamic x = 1;
{|stmt1:F|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="F")
result.AssertLabeledSpansAre("stmt1", "F", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(728646, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728646")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ExpandInvocationInStaticMemberAccess(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
}
}
class D
{
public void Sub()
{
C.{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "C.Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728628, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728628")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RecursiveTypeParameterExpansionFail(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
public void Sub()
{
C<int> x = new C<int>();
{|stmt1:Foo|}(x);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<C<int>>(x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(728575, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/728575")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameCrefWithProperBracesForTypeInferenceAdditionToMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename to Zoo
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Zoo")
result.AssertLabeledSpansAre("cref1", "Zoo{T}", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_GenericBase(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< { } // Rename Bar to Foo
}
class D : C<int>
{
public void Test()
{
{|stmt1:Foo|}(1);
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(1);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(639136, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/639136")>
<WpfTheory(Skip:="Story 736967"), CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub GenericNameTypeInferenceExpansion_InErrorCode(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< // Rename Bar to Foo
{
x = 1;
}
public void Test()
{
int y = 1;
int x;
{|stmt1:Foo|}(y, x); // error in code, but Foo is bound to Foo<T>
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Foo")
result.AssertLabeledSpansAre("stmt1", "Foo<int>(y, x);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
#End Region
<WorkItem(1016652, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016652")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CS_ConflictBetweenTypeNamesInTypeConstraintSyntax(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document><![CDATA[
using System.Collections.Generic;
// rename INamespaceSymbol to ISymbol
public interface {|unresolved1:$$INamespaceSymbol|} { }
public interface {|DeclConflict:ISymbol|} { }
public interface IReferenceFinder { }
internal abstract partial class AbstractReferenceFinder<TSymbol> : IReferenceFinder
where TSymbol : {|unresolved2:INamespaceSymbol|}
{
}]]></Document>
</Project>
</Workspace>, host:=host, renameTo:="ISymbol")
result.AssertLabeledSpansAre("DeclConflict", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved1", type:=RelatedLocationType.UnresolvedConflict)
result.AssertLabeledSpansAre("unresolved2", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_StaticReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
static void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingStatic(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
static int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfUsesTypeName_InstanceReferencingInstance(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
int zoo;
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(C.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1193, "https://github.com/dotnet/roslyn/issues/1193")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub MemberQualificationInNameOfMethodInvocationUsesThisDot(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class C
{
int zoo;
void F(int [|$$z|])
{
string x = nameof({|ref:zoo|});
}
void nameof(int x) { }
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="zoo")
result.AssertLabeledSpansAre("ref", "string x = nameof(this.zoo);", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInLambdaBodyExpression(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => 5;
static int N(long b) => 5;
System.Func<int, int> a = d => {|resolved:N|}(1);
System.Func<int> b = () => {|resolved:N|}(1);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved", "N((long)1)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1053, "https://github.com/dotnet/roslyn/issues/1053")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameComplexifiesInExpressionBodiedMembers(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs">< => {|resolved2:N|}(0);
int N(long b) => [|M|](0);
int P => {|resolved2:N|}(0);
}]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("resolved1", "new C().N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
result.AssertLabeledSpansAre("resolved2", "N((long)0)", RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
interface [|$$I|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndInterface2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class [|$$C|] { }
interface {|conflict:I|} { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="I")
result.AssertLabeledSpansAre("conflict", "I", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace1_FileScopedNamespace(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:$$C|} { }
namespace N;
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N")
result.AssertLabeledSpansAre("conflict", "N", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictBetweenClassAndNamespace2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
class {|conflict:C|} { }
namespace [|$$N|] { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C")
result.AssertLabeledSpansAre("conflict", "C", RelatedLocationType.UnresolvableConflict)
End Using
End Sub
<WorkItem(1027506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1027506")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictBetweenTwoNamespaces(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
namespace [|$$N1|][ { }
namespace N2 { }
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="N2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestNoConflictWithParametersOrLocalsOfDelegateType(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M1(Action [|callback$$|])
{
[|callback|]();
}
void M2(Func<bool> callback)
{
callback();
}
void M3()
{
Action callback = () => { };
callback();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="callback2")
End Using
End Sub
<WorkItem(1729, "https://github.com/dotnet/roslyn/issues/1729")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub TestConflictWithLocalsOfDelegateTypeWhenBindingChangesToNonDelegateLocal(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test.cs"><![CDATA[
using System;
class C
{
void M()
{
int [|x$$|] = 7; // Rename x to a. "a()" will bind to the first definition of a.
Action {|conflict:a|} = () => { };
{|conflict:a|}();
}
}
]]>
</Document>
</Project>
</Workspace>, host:=host, renameTo:="a")
result.AssertLabeledSpansAre("conflict", "a", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(446, "https://github.com/dotnet/roslyn/issues/446")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoCrashOrConflictOnRenameWithNameOfInAttribute(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
static void [|T|]$$(int x) { }
[System.Obsolete(nameof(Test))]
static void Test() { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceDoesNotBindToAnyOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
void Test()
{
int [|T$$|];
var x = nameof({|conflict:Test|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Test")
result.AssertLabeledSpansAre("conflict", "Test", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceDoesNotBindToSomeOriginalSymbols(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|$$M|](int x) { }
void M() { var x = nameof(M); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="X")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub NoConflictWhenNameOfReferenceBindsToSymbolForFirstTime(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
void [|X$$|]() { }
void M() { var x = nameof(T); }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
End Using
End Sub
<WorkItem(1195, "https://github.com/dotnet/roslyn/issues/1195")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenNameOfReferenceChangesBindingFromMetadataToSource(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
using System;
class Program
{
static void M()
{
var [|Consol$$|] = 7;
var x = nameof({|conflict:Console|});
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Console")
result.AssertLabeledSpansAre("conflict", "Console", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_IntroduceQualifiedName(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="C.D")
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", "C.D", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1031, "https://github.com/dotnet/roslyn/issues/1031")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub InvalidNamesDoNotCauseCrash_AccidentallyPasteLotsOfCode(host As RenameTestHost)
Dim renameTo = "class C { public void M() { for (int i = 0; i < 10; i++) { System.Console.Writeline(""This is a test""); } } }"
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class {|conflict:C$$|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:=renameTo)
result.AssertReplacementTextInvalid()
result.AssertLabeledSpansAre("conflict", renameTo, RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_SameProject(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
class Program
{
internal void [|A$$|]() { }
internal void {|conflict:B|}() { }
}
</Document>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_DifferentProjects(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly1">
<Document FilePath="Test1.cs">
public class Program
{
public void [|A$$|]() { }
public void {|conflict:B|}() { }
}
</Document>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSAssembly2">
<ProjectReference>CSAssembly1</ProjectReference>
<Document FilePath="Test2.cs">
class Program2
{
void M()
{
Program p = null;
p.{|conflict:A|}();
p.{|conflict:B|}();
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="B")
result.AssertLabeledSpansAre("conflict", "B", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(2352, "https://github.com/dotnet/roslyn/issues/2352")>
<WorkItem(3303, "https://github.com/dotnet/roslyn/issues/3303")>
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub DeclarationConflictInFileWithoutReferences_PartialTypes(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document FilePath="Test1.cs">
partial class C
{
private static void [|$$M|]()
{
{|conflict:M|}();
}
}
</Document>
<Document FilePath="Test2.cs">
partial class C
{
private static void {|conflict:Method|}()
{
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Method")
result.AssertLabeledSpansAre("conflict", "Method", RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf1(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|}).ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field).ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf2(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
nameof({|Conflict:field|})?.ToString(); // Should also expand to Program.field
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="nameof(Program.field)?.ToString();", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<WorkItem(1439, "https://github.com/dotnet/roslyn/issues/1439")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub RenameInsideNameOf3(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class Program
{
static int field;
static void Main(string[] args)
{
// Rename "local" to "field"
int [|$$local|];
Program.nameof({|Conflict:field|}); // Should also expand to Program.field
}
static void nameof(string s) { }
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="field")
result.AssertLabeledSpansAre("Conflict", replacement:="Program.nameof(Program.field);", type:=RelatedLocationType.ResolvedNonReferenceConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameTypeParameterInPartialClass(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<[|$$T|]> {}
partial class C<[|T|]> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T2")
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(7440, "https://github.com/dotnet/roslyn/issues/7440")>
Public Sub RenameMethodToConflictWithTypeParameter(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class C<{|Conflict:T|}> { void [|$$M|]() { } }
partial class C<{|Conflict:T|}> {}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="T")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(10469, "https://github.com/dotnet/roslyn/issues/10469")>
Public Sub RenameTypeToCurrent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
partial class {|current:$$C|} { }
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Current")
result.AssertLabeledSpansAre("current", type:=RelatedLocationType.NoConflict)
End Using
End Sub
<Theory>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
<WorkItem(16567, "https://github.com/dotnet/roslyn/issues/16567")>
Public Sub RenameMethodToFinalizeWithDestructorPresent(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
~{|Conflict:C|}() { }
void $$[|M|]()
{
int x = 7;
int y = ~x;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="Finalize")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(5872, "https://github.com/dotnet/roslyn/issues/5872")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub CannotRenameToVar(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class $${|Conflict:X|} {
{|Conflict:X|}() {
var a = 2;
}
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="var")
result.AssertLabeledSpansAre("Conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertySetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:set|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyInitterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { get; {|conflict:init|}; }
private void {|conflict:$$_set_MyProperty|}(int value) => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="set_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
<WpfTheory>
<WorkItem(45677, "https://github.com/dotnet/roslyn/issues/45677")>
<CombinatorialData, Trait(Traits.Feature, Traits.Features.Rename)>
Public Sub ConflictWhenRenamingPropertyGetterLikeMethod(host As RenameTestHost)
Using result = RenameEngineResult.Create(_outputHelper,
<Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
class C
{
public int MyProperty { {|conflict:get|}; set; }
private int {|conflict:$$_get_MyProperty|}() => throw null;
}
</Document>
</Project>
</Workspace>, host:=host, renameTo:="get_MyProperty")
result.AssertLabeledSpansAre("conflict", type:=RelatedLocationType.UnresolvedConflict)
End Using
End Sub
End Class
End Namespace
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/CodeGeneration/NamespaceGenerator.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class NamespaceGenerator
{
public static BaseNamespaceDeclarationSyntax AddNamespaceTo(
ICodeGenerationService service,
BaseNamespaceDeclarationSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
public static CompilationUnitSyntax AddNamespaceTo(
ICodeGenerationService service,
CompilationUnitSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
internal static SyntaxNode GenerateNamespaceDeclaration(
ICodeGenerationService service,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
options ??= CodeGenerationOptions.Default;
GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace);
var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options);
declaration = options.GenerateMembers
? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken)
: declaration;
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration(
ICodeGenerationService service,
SyntaxNode declaration,
IList<ISymbol> newMembers,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
declaration = RemoveAllMembers(declaration);
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken);
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
private static SyntaxNode GenerateNamespaceDeclarationWorker(
string name, INamespaceSymbol innermostNamespace)
{
var usings = GenerateUsingDirectives(innermostNamespace);
// If they're just generating the empty namespace then make that into compilation unit.
if (name == string.Empty)
{
return SyntaxFactory.CompilationUnit().WithUsings(usings);
}
return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings);
}
private static SyntaxNode GetDeclarationSyntaxWithoutMembers(
INamespaceSymbol @namespace,
INamespaceSymbol innermostNamespace,
string name,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options);
if (reusableSyntax == null)
{
return GenerateNamespaceDeclarationWorker(name, innermostNamespace);
}
return RemoveAllMembers(reusableSyntax);
}
private static SyntaxNode RemoveAllMembers(SyntaxNode declaration)
=> declaration switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default),
BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default),
_ => declaration,
};
private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace)
{
var usingDirectives =
CodeGenerationNamespaceInfo.GetImports(innermostNamespace)
.Select(GenerateUsingDirective)
.WhereNotNull()
.ToList();
return usingDirectives.ToSyntaxList();
}
private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol)
{
if (symbol is IAliasSymbol alias)
{
var name = GenerateName(alias.Target);
if (name != null)
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()),
name);
}
}
else if (symbol is INamespaceOrTypeSymbol namespaceOrType)
{
var name = GenerateName(namespaceOrType);
if (name != null)
{
return SyntaxFactory.UsingDirective(name);
}
}
return null;
}
private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol)
{
if (symbol is ITypeSymbol type)
{
return type.GenerateTypeSyntax() as NameSyntax;
}
else
{
return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers;
using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers;
namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration
{
internal static class NamespaceGenerator
{
public static BaseNamespaceDeclarationSyntax AddNamespaceTo(
ICodeGenerationService service,
BaseNamespaceDeclarationSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not BaseNamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
public static CompilationUnitSyntax AddNamespaceTo(
ICodeGenerationService service,
CompilationUnitSyntax destination,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
IList<bool> availableIndices,
CancellationToken cancellationToken)
{
var declaration = GenerateNamespaceDeclaration(service, @namespace, options, cancellationToken);
if (declaration is not NamespaceDeclarationSyntax namespaceDeclaration)
throw new ArgumentException(CSharpWorkspaceResources.Namespace_can_not_be_added_in_this_destination);
var members = Insert(destination.Members, namespaceDeclaration, options, availableIndices);
return destination.WithMembers(members);
}
internal static SyntaxNode GenerateNamespaceDeclaration(
ICodeGenerationService service,
INamespaceSymbol @namespace,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
options ??= CodeGenerationOptions.Default;
GetNameAndInnermostNamespace(@namespace, options, out var name, out var innermostNamespace);
var declaration = GetDeclarationSyntaxWithoutMembers(@namespace, innermostNamespace, name, options);
declaration = options.GenerateMembers
? service.AddMembers(declaration, innermostNamespace.GetMembers(), options, cancellationToken)
: declaration;
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
public static SyntaxNode UpdateCompilationUnitOrNamespaceDeclaration(
ICodeGenerationService service,
SyntaxNode declaration,
IList<ISymbol> newMembers,
CodeGenerationOptions options,
CancellationToken cancellationToken)
{
declaration = RemoveAllMembers(declaration);
declaration = service.AddMembers(declaration, newMembers, options, cancellationToken);
return AddFormatterAndCodeGeneratorAnnotationsTo(declaration);
}
private static SyntaxNode GenerateNamespaceDeclarationWorker(
string name, INamespaceSymbol innermostNamespace)
{
var usings = GenerateUsingDirectives(innermostNamespace);
// If they're just generating the empty namespace then make that into compilation unit.
if (name == string.Empty)
{
return SyntaxFactory.CompilationUnit().WithUsings(usings);
}
return SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(name)).WithUsings(usings);
}
private static SyntaxNode GetDeclarationSyntaxWithoutMembers(
INamespaceSymbol @namespace,
INamespaceSymbol innermostNamespace,
string name,
CodeGenerationOptions options)
{
var reusableSyntax = GetReuseableSyntaxNodeForSymbol<SyntaxNode>(@namespace, options);
if (reusableSyntax == null)
{
return GenerateNamespaceDeclarationWorker(name, innermostNamespace);
}
return RemoveAllMembers(reusableSyntax);
}
private static SyntaxNode RemoveAllMembers(SyntaxNode declaration)
=> declaration switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.WithMembers(default),
BaseNamespaceDeclarationSyntax namespaceDeclaration => namespaceDeclaration.WithMembers(default),
_ => declaration,
};
private static SyntaxList<UsingDirectiveSyntax> GenerateUsingDirectives(INamespaceSymbol innermostNamespace)
{
var usingDirectives =
CodeGenerationNamespaceInfo.GetImports(innermostNamespace)
.Select(GenerateUsingDirective)
.WhereNotNull()
.ToList();
return usingDirectives.ToSyntaxList();
}
private static UsingDirectiveSyntax GenerateUsingDirective(ISymbol symbol)
{
if (symbol is IAliasSymbol alias)
{
var name = GenerateName(alias.Target);
if (name != null)
{
return SyntaxFactory.UsingDirective(
SyntaxFactory.NameEquals(alias.Name.ToIdentifierName()),
name);
}
}
else if (symbol is INamespaceOrTypeSymbol namespaceOrType)
{
var name = GenerateName(namespaceOrType);
if (name != null)
{
return SyntaxFactory.UsingDirective(name);
}
}
return null;
}
private static NameSyntax GenerateName(INamespaceOrTypeSymbol symbol)
{
if (symbol is ITypeSymbol type)
{
return type.GenerateTypeSyntax() as NameSyntax;
}
else
{
return SyntaxFactory.ParseName(symbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat));
}
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/OrganizeImports/CSharpOrganizeImportsService.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.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports
{
internal partial class CSharpOrganizeImportsService
{
private class Rewriter : CSharpSyntaxRewriter
{
private readonly bool _placeSystemNamespaceFirst;
private readonly bool _separateGroups;
public readonly IList<TextChange> TextChanges = new List<TextChange>();
public Rewriter(bool placeSystemNamespaceFirst,
bool separateGroups)
{
_placeSystemNamespaceFirst = placeSystemNamespaceFirst;
_separateGroups = separateGroups;
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!;
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node));
public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node));
private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node)
{
Contract.ThrowIfNull(node);
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList)
where TSyntax : SyntaxNode
{
if (list.Count > 0)
this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList)));
}
private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode
=> string.Join(string.Empty, organizedList.Select(t => t.ToFullString()));
private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode
=> TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.OrganizeImports
{
internal partial class CSharpOrganizeImportsService
{
private class Rewriter : CSharpSyntaxRewriter
{
private readonly bool _placeSystemNamespaceFirst;
private readonly bool _separateGroups;
public readonly IList<TextChange> TextChanges = new List<TextChange>();
public Rewriter(bool placeSystemNamespaceFirst,
bool separateGroups)
{
_placeSystemNamespaceFirst = placeSystemNamespaceFirst;
_separateGroups = separateGroups;
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
node = (CompilationUnitSyntax)base.VisitCompilationUnit(node)!;
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
public override SyntaxNode VisitFileScopedNamespaceDeclaration(FileScopedNamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitFileScopedNamespaceDeclaration(node));
public override SyntaxNode VisitNamespaceDeclaration(NamespaceDeclarationSyntax node)
=> VisitBaseNamespaceDeclaration((BaseNamespaceDeclarationSyntax?)base.VisitNamespaceDeclaration(node));
private BaseNamespaceDeclarationSyntax VisitBaseNamespaceDeclaration(BaseNamespaceDeclarationSyntax? node)
{
Contract.ThrowIfNull(node);
UsingsAndExternAliasesOrganizer.Organize(
node.Externs, node.Usings,
_placeSystemNamespaceFirst, _separateGroups,
out var organizedExternAliasList, out var organizedUsingList);
var result = node.WithExterns(organizedExternAliasList).WithUsings(organizedUsingList);
if (node != result)
{
AddTextChange(node.Externs, organizedExternAliasList);
AddTextChange(node.Usings, organizedUsingList);
}
return result;
}
private void AddTextChange<TSyntax>(SyntaxList<TSyntax> list, SyntaxList<TSyntax> organizedList)
where TSyntax : SyntaxNode
{
if (list.Count > 0)
this.TextChanges.Add(new TextChange(GetTextSpan(list), GetNewText(organizedList)));
}
private static string GetNewText<TSyntax>(SyntaxList<TSyntax> organizedList) where TSyntax : SyntaxNode
=> string.Join(string.Empty, organizedList.Select(t => t.ToFullString()));
private static TextSpan GetTextSpan<TSyntax>(SyntaxList<TSyntax> list) where TSyntax : SyntaxNode
=> TextSpan.FromBounds(list.First().FullSpan.Start, list.Last().FullSpan.End);
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/Recommendations/CSharpRecommendationServiceRunner.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Recommendations
{
internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext>
{
public CSharpRecommendationServiceRunner(
CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken)
: base(context, filterOutOfScopeLocals, cancellationToken)
{
}
public override RecommendedSymbols GetRecommendedSymbols()
{
if (_context.IsInNonUserCode ||
_context.IsPreProcessorDirectiveContext)
{
return default;
}
if (!_context.IsRightOfNameSeparator)
return new RecommendedSymbols(GetSymbolsForCurrentContext());
return GetSymbolsOffOfContainer();
}
public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType)
{
if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax))
{
var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters;
if (parameters.Count > ordinalInLambda)
{
var parameter = parameters[ordinalInLambda];
if (parameter.Type != null)
{
explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type;
return explicitLambdaParameterType != null;
}
}
}
// Non-parenthesized lambdas cannot explicitly specify the type of the single parameter
explicitLambdaParameterType = null;
return false;
}
private ImmutableArray<ISymbol> GetSymbolsForCurrentContext()
{
if (_context.IsGlobalStatementContext)
{
// Script and interactive
return GetSymbolsForGlobalStatementContext();
}
else if (_context.IsAnyExpressionContext ||
_context.IsStatementContext ||
_context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken))
{
// GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as
// as cast. The user might be trying to type a parenthesized expression, so even though a cast
// is a type-only context, we'll show all symbols anyway.
return GetSymbolsForExpressionOrStatementContext();
}
else if (_context.IsTypeContext || _context.IsNamespaceContext)
{
return GetSymbolsForTypeOrNamespaceContext();
}
else if (_context.IsLabelContext)
{
return GetSymbolsForLabelContext();
}
else if (_context.IsTypeArgumentOfConstraintContext)
{
return GetSymbolsForTypeArgumentOfConstraintClause();
}
else if (_context.IsDestructorTypeContext)
{
var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken);
return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol);
}
else if (_context.IsNamespaceDeclarationNameContext)
{
return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>();
}
return ImmutableArray<ISymbol>.Empty;
}
private RecommendedSymbols GetSymbolsOffOfContainer()
{
// Ensure that we have the correct token in A.B| case
var node = _context.TargetToken.GetRequiredParent();
return node switch
{
MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess
=> GetSymbolsOffOfExpression(memberAccess.Expression),
MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess
=> GetSymbolsOffOfDereferencedExpression(memberAccess.Expression),
// This code should be executing only if the cursor is between two dots in a dotdot token.
RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand),
QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left),
AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias),
MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression),
_ => default,
};
}
private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext()
{
var syntaxTree = _context.SyntaxTree;
var position = _context.Position;
var token = _context.LeftToken;
// The following code is a hack to get around a binding problem when asking binding
// questions immediately after a using directive. This is special-cased in the binder
// factory to ensure that using directives are not within scope inside other using
// directives. That generally works fine for .cs, but it's a problem for interactive
// code in this case:
//
// using System;
// |
if (token.Kind() == SyntaxKind.SemicolonToken &&
token.Parent.IsKind(SyntaxKind.UsingDirective) &&
position >= token.Span.End)
{
var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken);
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token)
{
token = token.GetNextToken(includeZeroWidth: true);
}
}
var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart);
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause()
{
var enclosingSymbol = _context.LeftToken.GetRequiredParent()
.AncestorsAndSelf()
.Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken))
.WhereNotNull()
.FirstOrDefault();
var symbols = enclosingSymbol != null
? enclosingSymbol.GetTypeArguments()
: ImmutableArray<ITypeSymbol>.Empty;
return ImmutableArray<ISymbol>.CastUp(symbols);
}
private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias)
{
var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken);
if (aliasSymbol == null)
return default;
return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes(
alias.SpanStart,
aliasSymbol.Target));
}
private ImmutableArray<ISymbol> GetSymbolsForLabelContext()
{
var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart);
// Exclude labels (other than 'default') that come from case switch statements
return allLabels
.WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken)
.IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel));
}
private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext()
{
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart);
if (_context.TargetToken.IsUsingKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => s.IsNamespace());
}
if (_context.TargetToken.IsStaticKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType());
}
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext()
{
// Check if we're in an interesting situation like this:
//
// i // <-- here
// I = 0;
// The problem is that "i I = 0" causes a local to be in scope called "I". So, later when
// we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that
// name). If this is the case, we do not want to filter out inaccessible locals.
var filterOutOfScopeLocals = _filterOutOfScopeLocals;
if (filterOutOfScopeLocals)
filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type);
var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext()
? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart)
: _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart);
// Filter out any extension methods that might be imported by a using static directive.
// But include extension methods declared in the context's type or it's parents
var contextOuterTypes = _context.GetOuterTypes(_cancellationToken);
var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
symbols = symbols.WhereAsArray(symbol =>
!symbol.IsExtensionMethod() ||
Equals(contextEnclosingNamedType, symbol.ContainingType) ||
contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType)));
// The symbols may include local variables that are declared later in the method and
// should not be included in the completion list, so remove those. Filter them away,
// unless we're in the debugger, where we show all locals in scope.
if (filterOutOfScopeLocals)
{
symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position));
}
return symbols;
}
private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name)
{
// Using an is pattern on an enum is a qualified name, but normal symbol processing works fine
if (_context.IsEnumTypeMemberAccessContext)
return GetSymbolsOffOfExpression(name);
if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container))
return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false);
// We're in a name-only context, since if we were an expression we'd be a
// MemberAccessExpressionSyntax. Thus, let's do other namespaces and types.
nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken);
if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol)
return default;
if (_context.IsNameOfContext)
return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol));
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(
position: name.SpanStart,
container: symbol);
if (_context.IsNamespaceDeclarationNameContext)
{
var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>();
return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax)));
}
// Filter the types when in a using directive, but not an alias.
//
// Cases:
// using | -- Show namespaces
// using A.| -- Show namespaces
// using static | -- Show namespace and types
// using A = B.| -- Show namespace and types
var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirective != null && usingDirective.Alias == null)
{
return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)
? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType())
: symbols.WhereAsArray(s => s.IsNamespace()));
}
return new RecommendedSymbols(symbols);
}
/// <summary>
/// DeterminesCheck if we're in an interesting situation like this:
/// <code>
/// int i = 5;
/// i. // -- here
/// List ml = new List();
/// </code>
/// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is
/// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't
/// part of a local declaration's type.
/// <para/>
/// Another interesting case is something like:
/// <code>
/// stringList.
/// await Test2();
/// </code>
/// Here "stringList.await" is thought of as the return type of a local function.
/// </summary>
private bool ShouldBeTreatedAsTypeInsteadOfExpression(
ExpressionSyntax name,
out SymbolInfo leftHandBinding,
out ITypeSymbol? container)
{
if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) ||
name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) ||
name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type))
{
leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression);
container = _context.SemanticModel.GetSpeculativeTypeInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type;
return true;
}
leftHandBinding = default;
container = null;
return false;
}
private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression)
{
if (originalExpression == null)
return default;
// In case of 'await x$$', we want to move to 'x' to get it's members.
// To run GetSymbolInfo, we also need to get rid of parenthesis.
var expression = originalExpression is AwaitExpressionSyntax awaitExpression
? awaitExpression.Expression.WalkDownParentheses()
: originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
// Check for the Color Color case.
if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken))
{
var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace);
var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false);
result = new RecommendedSymbols(
result.NamedSymbols.Concat(typeMembers.NamedSymbols),
result.UnnamedSymbols);
}
return result;
}
private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression)
{
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
if (container is IPointerTypeSymbol pointerType)
{
container = pointerType.PointedAtType;
}
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
}
private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression)
{
// Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly,
// a member access off of a conditional receiver of nullable type binds to the unwrapped nullable
// type. This is not exposed via the binding information for the LHS, so repeat this work here.
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
// If the thing on the left is a type, namespace, or alias, we shouldn't show anything in
// IntelliSense.
if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias))
return default;
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true);
}
private RecommendedSymbols GetSymbolsOffOfBoundExpression(
ExpressionSyntax originalExpression,
ExpressionSyntax expression,
SymbolInfo leftHandBinding,
ITypeSymbol? containerType,
bool unwrapNullable)
{
var abstractsOnly = false;
var excludeInstance = false;
var excludeStatic = true;
ISymbol? containerSymbol = containerType;
var symbol = leftHandBinding.GetAnySymbol();
if (symbol != null)
{
// If the thing on the left is a lambda expression, we shouldn't show anything.
if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction })
return default;
var originalExpressionKind = originalExpression.Kind();
// If the thing on the left is a type, namespace or alias and the original
// expression was parenthesized, we shouldn't show anything in IntelliSense.
if (originalExpressionKind is SyntaxKind.ParenthesizedExpression &&
symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias)
{
return default;
}
// If the thing on the left is a method name identifier, we shouldn't show anything.
if (symbol.Kind is SymbolKind.Method &&
originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName)
{
return default;
}
// If the thing on the left is an event that can't be used as a field, we shouldn't show anything
if (symbol is IEventSymbol ev &&
!_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev))
{
return default;
}
if (symbol is IAliasSymbol alias)
symbol = alias.Target;
if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter)
{
// For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around.
// We only want statics and not instance members.
excludeInstance = true;
excludeStatic = false;
abstractsOnly = symbol.Kind == SymbolKind.TypeParameter;
containerSymbol = symbol;
}
// Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to
// lookup symbols off of as we have a lot of special logic for determining member symbols of lambda
// parameters.
//
// If it is a this/base parameter and we're in a static context, we shouldn't show anything
if (symbol is IParameterSymbol parameter)
{
if (parameter.IsThis && expression.IsInStaticContext())
return default;
containerSymbol = symbol;
}
}
else if (containerType != null)
{
// Otherwise, if it wasn't a symbol on the left, but it was something that had a type,
// then include instance members for it.
excludeStatic = true;
}
if (containerSymbol == null)
return default;
Debug.Assert(!excludeInstance || !excludeStatic);
Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance));
// nameof(X.|
// Show static and instance members.
if (_context.IsNameOfContext)
{
excludeInstance = false;
excludeStatic = false;
}
var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType);
var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable);
// If we're showing instance members, don't include nested types
var namedSymbols = excludeStatic
? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol))
: (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols);
// if we're dotting off an instance, then add potential operators/indexers/conversions that may be
// applicable to it as well.
var unnamedSymbols = _context.IsNameOfContext || excludeInstance
? default
: GetUnnamedSymbols(originalExpression);
return new RecommendedSymbols(namedSymbols, unnamedSymbols);
}
private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression)
{
var semanticModel = _context.SemanticModel;
var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression);
if (container == null)
return ImmutableArray<ISymbol>.Empty;
// In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not
// `int?`. However, we want to think of the constructed type as that's the type of the overall expression
// that will be casted.
if (originalExpression.GetRootConditionalAccessExpression() != null)
container = TryMakeNullable(semanticModel.Compilation, container);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
AddIndexers(container, symbols);
AddOperators(container, symbols);
AddConversions(container, symbols);
return symbols.ToImmutable();
}
private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression)
{
return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container)
? container
: semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type;
}
private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols)
{
var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
if (containingType == null)
return;
foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType))
{
if (member.IsIndexer)
symbols.Add(member);
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Recommendations;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Recommendations
{
internal partial class CSharpRecommendationServiceRunner : AbstractRecommendationServiceRunner<CSharpSyntaxContext>
{
public CSharpRecommendationServiceRunner(
CSharpSyntaxContext context, bool filterOutOfScopeLocals, CancellationToken cancellationToken)
: base(context, filterOutOfScopeLocals, cancellationToken)
{
}
public override RecommendedSymbols GetRecommendedSymbols()
{
if (_context.IsInNonUserCode ||
_context.IsPreProcessorDirectiveContext)
{
return default;
}
if (!_context.IsRightOfNameSeparator)
return new RecommendedSymbols(GetSymbolsForCurrentContext());
return GetSymbolsOffOfContainer();
}
public override bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(true)] out ITypeSymbol? explicitLambdaParameterType)
{
if (lambdaSyntax.IsKind<ParenthesizedLambdaExpressionSyntax>(SyntaxKind.ParenthesizedLambdaExpression, out var parenthesizedLambdaSyntax))
{
var parameters = parenthesizedLambdaSyntax.ParameterList.Parameters;
if (parameters.Count > ordinalInLambda)
{
var parameter = parameters[ordinalInLambda];
if (parameter.Type != null)
{
explicitLambdaParameterType = _context.SemanticModel.GetTypeInfo(parameter.Type, _cancellationToken).Type;
return explicitLambdaParameterType != null;
}
}
}
// Non-parenthesized lambdas cannot explicitly specify the type of the single parameter
explicitLambdaParameterType = null;
return false;
}
private ImmutableArray<ISymbol> GetSymbolsForCurrentContext()
{
if (_context.IsGlobalStatementContext)
{
// Script and interactive
return GetSymbolsForGlobalStatementContext();
}
else if (_context.IsAnyExpressionContext ||
_context.IsStatementContext ||
_context.SyntaxTree.IsDefiniteCastTypeContext(_context.Position, _context.LeftToken))
{
// GitHub #717: With automatic brace completion active, typing '(i' produces "(i)", which gets parsed as
// as cast. The user might be trying to type a parenthesized expression, so even though a cast
// is a type-only context, we'll show all symbols anyway.
return GetSymbolsForExpressionOrStatementContext();
}
else if (_context.IsTypeContext || _context.IsNamespaceContext)
{
return GetSymbolsForTypeOrNamespaceContext();
}
else if (_context.IsLabelContext)
{
return GetSymbolsForLabelContext();
}
else if (_context.IsTypeArgumentOfConstraintContext)
{
return GetSymbolsForTypeArgumentOfConstraintClause();
}
else if (_context.IsDestructorTypeContext)
{
var symbol = _context.SemanticModel.GetDeclaredSymbol(_context.ContainingTypeOrEnumDeclaration!, _cancellationToken);
return symbol == null ? ImmutableArray<ISymbol>.Empty : ImmutableArray.Create<ISymbol>(symbol);
}
else if (_context.IsNamespaceDeclarationNameContext)
{
return GetSymbolsForNamespaceDeclarationNameContext<BaseNamespaceDeclarationSyntax>();
}
return ImmutableArray<ISymbol>.Empty;
}
private RecommendedSymbols GetSymbolsOffOfContainer()
{
// Ensure that we have the correct token in A.B| case
var node = _context.TargetToken.GetRequiredParent();
return node switch
{
MemberAccessExpressionSyntax(SyntaxKind.SimpleMemberAccessExpression) memberAccess
=> GetSymbolsOffOfExpression(memberAccess.Expression),
MemberAccessExpressionSyntax(SyntaxKind.PointerMemberAccessExpression) memberAccess
=> GetSymbolsOffOfDereferencedExpression(memberAccess.Expression),
// This code should be executing only if the cursor is between two dots in a dotdot token.
RangeExpressionSyntax rangeExpression => GetSymbolsOffOfExpression(rangeExpression.LeftOperand),
QualifiedNameSyntax qualifiedName => GetSymbolsOffOfName(qualifiedName.Left),
AliasQualifiedNameSyntax aliasName => GetSymbolsOffOffAlias(aliasName.Alias),
MemberBindingExpressionSyntax _ => GetSymbolsOffOfConditionalReceiver(node.GetParentConditionalAccessExpression()!.Expression),
_ => default,
};
}
private ImmutableArray<ISymbol> GetSymbolsForGlobalStatementContext()
{
var syntaxTree = _context.SyntaxTree;
var position = _context.Position;
var token = _context.LeftToken;
// The following code is a hack to get around a binding problem when asking binding
// questions immediately after a using directive. This is special-cased in the binder
// factory to ensure that using directives are not within scope inside other using
// directives. That generally works fine for .cs, but it's a problem for interactive
// code in this case:
//
// using System;
// |
if (token.Kind() == SyntaxKind.SemicolonToken &&
token.Parent.IsKind(SyntaxKind.UsingDirective) &&
position >= token.Span.End)
{
var compUnit = (CompilationUnitSyntax)syntaxTree.GetRoot(_cancellationToken);
if (compUnit.Usings.Count > 0 && compUnit.Usings.Last().GetLastToken() == token)
{
token = token.GetNextToken(includeZeroWidth: true);
}
}
var symbols = _context.SemanticModel.LookupSymbols(token.SpanStart);
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForTypeArgumentOfConstraintClause()
{
var enclosingSymbol = _context.LeftToken.GetRequiredParent()
.AncestorsAndSelf()
.Select(n => _context.SemanticModel.GetDeclaredSymbol(n, _cancellationToken))
.WhereNotNull()
.FirstOrDefault();
var symbols = enclosingSymbol != null
? enclosingSymbol.GetTypeArguments()
: ImmutableArray<ITypeSymbol>.Empty;
return ImmutableArray<ISymbol>.CastUp(symbols);
}
private RecommendedSymbols GetSymbolsOffOffAlias(IdentifierNameSyntax alias)
{
var aliasSymbol = _context.SemanticModel.GetAliasInfo(alias, _cancellationToken);
if (aliasSymbol == null)
return default;
return new RecommendedSymbols(_context.SemanticModel.LookupNamespacesAndTypes(
alias.SpanStart,
aliasSymbol.Target));
}
private ImmutableArray<ISymbol> GetSymbolsForLabelContext()
{
var allLabels = _context.SemanticModel.LookupLabels(_context.LeftToken.SpanStart);
// Exclude labels (other than 'default') that come from case switch statements
return allLabels
.WhereAsArray(label => label.DeclaringSyntaxReferences.First().GetSyntax(_cancellationToken)
.IsKind(SyntaxKind.LabeledStatement, SyntaxKind.DefaultSwitchLabel));
}
private ImmutableArray<ISymbol> GetSymbolsForTypeOrNamespaceContext()
{
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(_context.LeftToken.SpanStart);
if (_context.TargetToken.IsUsingKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => s.IsNamespace());
}
if (_context.TargetToken.IsStaticKeywordInUsingDirective())
{
return symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType());
}
return symbols;
}
private ImmutableArray<ISymbol> GetSymbolsForExpressionOrStatementContext()
{
// Check if we're in an interesting situation like this:
//
// i // <-- here
// I = 0;
// The problem is that "i I = 0" causes a local to be in scope called "I". So, later when
// we look up symbols, it masks any other 'I's in scope (i.e. if there's a field with that
// name). If this is the case, we do not want to filter out inaccessible locals.
var filterOutOfScopeLocals = _filterOutOfScopeLocals;
if (filterOutOfScopeLocals)
filterOutOfScopeLocals = !_context.LeftToken.GetRequiredParent().IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type);
var symbols = !_context.IsNameOfContext && _context.LeftToken.GetRequiredParent().IsInStaticContext()
? _context.SemanticModel.LookupStaticMembers(_context.LeftToken.SpanStart)
: _context.SemanticModel.LookupSymbols(_context.LeftToken.SpanStart);
// Filter out any extension methods that might be imported by a using static directive.
// But include extension methods declared in the context's type or it's parents
var contextOuterTypes = _context.GetOuterTypes(_cancellationToken);
var contextEnclosingNamedType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
symbols = symbols.WhereAsArray(symbol =>
!symbol.IsExtensionMethod() ||
Equals(contextEnclosingNamedType, symbol.ContainingType) ||
contextOuterTypes.Any(outerType => outerType.Equals(symbol.ContainingType)));
// The symbols may include local variables that are declared later in the method and
// should not be included in the completion list, so remove those. Filter them away,
// unless we're in the debugger, where we show all locals in scope.
if (filterOutOfScopeLocals)
{
symbols = symbols.WhereAsArray(symbol => !symbol.IsInaccessibleLocal(_context.Position));
}
return symbols;
}
private RecommendedSymbols GetSymbolsOffOfName(NameSyntax name)
{
// Using an is pattern on an enum is a qualified name, but normal symbol processing works fine
if (_context.IsEnumTypeMemberAccessContext)
return GetSymbolsOffOfExpression(name);
if (ShouldBeTreatedAsTypeInsteadOfExpression(name, out var nameBinding, out var container))
return GetSymbolsOffOfBoundExpression(name, name, nameBinding, container, unwrapNullable: false);
// We're in a name-only context, since if we were an expression we'd be a
// MemberAccessExpressionSyntax. Thus, let's do other namespaces and types.
nameBinding = _context.SemanticModel.GetSymbolInfo(name, _cancellationToken);
if (nameBinding.Symbol is not INamespaceOrTypeSymbol symbol)
return default;
if (_context.IsNameOfContext)
return new RecommendedSymbols(_context.SemanticModel.LookupSymbols(position: name.SpanStart, container: symbol));
var symbols = _context.SemanticModel.LookupNamespacesAndTypes(
position: name.SpanStart,
container: symbol);
if (_context.IsNamespaceDeclarationNameContext)
{
var declarationSyntax = name.GetAncestorOrThis<BaseNamespaceDeclarationSyntax>();
return new RecommendedSymbols(symbols.WhereAsArray(s => IsNonIntersectingNamespace(s, declarationSyntax)));
}
// Filter the types when in a using directive, but not an alias.
//
// Cases:
// using | -- Show namespaces
// using A.| -- Show namespaces
// using static | -- Show namespace and types
// using A = B.| -- Show namespace and types
var usingDirective = name.GetAncestorOrThis<UsingDirectiveSyntax>();
if (usingDirective != null && usingDirective.Alias == null)
{
return new RecommendedSymbols(usingDirective.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)
? symbols.WhereAsArray(s => !s.IsDelegateType() && !s.IsInterfaceType())
: symbols.WhereAsArray(s => s.IsNamespace()));
}
return new RecommendedSymbols(symbols);
}
/// <summary>
/// DeterminesCheck if we're in an interesting situation like this:
/// <code>
/// int i = 5;
/// i. // -- here
/// List ml = new List();
/// </code>
/// The problem is that "i.List" gets parsed as a type. In this case we need to try binding again as if "i" is
/// an expression and not a type. In order to do that, we need to speculate as to what 'i' meant if it wasn't
/// part of a local declaration's type.
/// <para/>
/// Another interesting case is something like:
/// <code>
/// stringList.
/// await Test2();
/// </code>
/// Here "stringList.await" is thought of as the return type of a local function.
/// </summary>
private bool ShouldBeTreatedAsTypeInsteadOfExpression(
ExpressionSyntax name,
out SymbolInfo leftHandBinding,
out ITypeSymbol? container)
{
if (name.IsFoundUnder<LocalFunctionStatementSyntax>(d => d.ReturnType) ||
name.IsFoundUnder<LocalDeclarationStatementSyntax>(d => d.Declaration.Type) ||
name.IsFoundUnder<FieldDeclarationSyntax>(d => d.Declaration.Type))
{
leftHandBinding = _context.SemanticModel.GetSpeculativeSymbolInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression);
container = _context.SemanticModel.GetSpeculativeTypeInfo(
name.SpanStart, name, SpeculativeBindingOption.BindAsExpression).Type;
return true;
}
leftHandBinding = default;
container = null;
return false;
}
private RecommendedSymbols GetSymbolsOffOfExpression(ExpressionSyntax? originalExpression)
{
if (originalExpression == null)
return default;
// In case of 'await x$$', we want to move to 'x' to get it's members.
// To run GetSymbolInfo, we also need to get rid of parenthesis.
var expression = originalExpression is AwaitExpressionSyntax awaitExpression
? awaitExpression.Expression.WalkDownParentheses()
: originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
var result = GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
// Check for the Color Color case.
if (originalExpression.CanAccessInstanceAndStaticMembersOffOf(_context.SemanticModel, _cancellationToken))
{
var speculativeSymbolInfo = _context.SemanticModel.GetSpeculativeSymbolInfo(expression.SpanStart, expression, SpeculativeBindingOption.BindAsTypeOrNamespace);
var typeMembers = GetSymbolsOffOfBoundExpression(originalExpression, expression, speculativeSymbolInfo, container, unwrapNullable: false);
result = new RecommendedSymbols(
result.NamedSymbols.Concat(typeMembers.NamedSymbols),
result.UnnamedSymbols);
}
return result;
}
private RecommendedSymbols GetSymbolsOffOfDereferencedExpression(ExpressionSyntax originalExpression)
{
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
if (container is IPointerTypeSymbol pointerType)
{
container = pointerType.PointedAtType;
}
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: false);
}
private RecommendedSymbols GetSymbolsOffOfConditionalReceiver(ExpressionSyntax originalExpression)
{
// Given ((T?)t)?.|, the '.' will behave as if the expression was actually ((T)t).|. More plainly,
// a member access off of a conditional receiver of nullable type binds to the unwrapped nullable
// type. This is not exposed via the binding information for the LHS, so repeat this work here.
var expression = originalExpression.WalkDownParentheses();
var leftHandBinding = _context.SemanticModel.GetSymbolInfo(expression, _cancellationToken);
var container = _context.SemanticModel.GetTypeInfo(expression, _cancellationToken).Type;
// If the thing on the left is a type, namespace, or alias, we shouldn't show anything in
// IntelliSense.
if (leftHandBinding.GetBestOrAllSymbols().FirstOrDefault().MatchesKind(SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Alias))
return default;
return GetSymbolsOffOfBoundExpression(originalExpression, expression, leftHandBinding, container, unwrapNullable: true);
}
private RecommendedSymbols GetSymbolsOffOfBoundExpression(
ExpressionSyntax originalExpression,
ExpressionSyntax expression,
SymbolInfo leftHandBinding,
ITypeSymbol? containerType,
bool unwrapNullable)
{
var abstractsOnly = false;
var excludeInstance = false;
var excludeStatic = true;
ISymbol? containerSymbol = containerType;
var symbol = leftHandBinding.GetAnySymbol();
if (symbol != null)
{
// If the thing on the left is a lambda expression, we shouldn't show anything.
if (symbol is IMethodSymbol { MethodKind: MethodKind.AnonymousFunction })
return default;
var originalExpressionKind = originalExpression.Kind();
// If the thing on the left is a type, namespace or alias and the original
// expression was parenthesized, we shouldn't show anything in IntelliSense.
if (originalExpressionKind is SyntaxKind.ParenthesizedExpression &&
symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.Alias)
{
return default;
}
// If the thing on the left is a method name identifier, we shouldn't show anything.
if (symbol.Kind is SymbolKind.Method &&
originalExpressionKind is SyntaxKind.IdentifierName or SyntaxKind.GenericName)
{
return default;
}
// If the thing on the left is an event that can't be used as a field, we shouldn't show anything
if (symbol is IEventSymbol ev &&
!_context.SemanticModel.IsEventUsableAsField(originalExpression.SpanStart, ev))
{
return default;
}
if (symbol is IAliasSymbol alias)
symbol = alias.Target;
if (symbol.Kind is SymbolKind.NamedType or SymbolKind.Namespace or SymbolKind.TypeParameter)
{
// For named typed, namespaces, and type parameters (potentially constrainted to interface with statics), we flip things around.
// We only want statics and not instance members.
excludeInstance = true;
excludeStatic = false;
abstractsOnly = symbol.Kind == SymbolKind.TypeParameter;
containerSymbol = symbol;
}
// Special case parameters. If we have a normal (non this/base) parameter, then that's what we want to
// lookup symbols off of as we have a lot of special logic for determining member symbols of lambda
// parameters.
//
// If it is a this/base parameter and we're in a static context, we shouldn't show anything
if (symbol is IParameterSymbol parameter)
{
if (parameter.IsThis && expression.IsInStaticContext())
return default;
containerSymbol = symbol;
}
}
else if (containerType != null)
{
// Otherwise, if it wasn't a symbol on the left, but it was something that had a type,
// then include instance members for it.
excludeStatic = true;
}
if (containerSymbol == null)
return default;
Debug.Assert(!excludeInstance || !excludeStatic);
Debug.Assert(!abstractsOnly || (abstractsOnly && !excludeStatic && excludeInstance));
// nameof(X.|
// Show static and instance members.
if (_context.IsNameOfContext)
{
excludeInstance = false;
excludeStatic = false;
}
var useBaseReferenceAccessibility = symbol is IParameterSymbol { IsThis: true } p && !p.Type.Equals(containerType);
var symbols = GetMemberSymbols(containerSymbol, position: originalExpression.SpanStart, excludeInstance, useBaseReferenceAccessibility, unwrapNullable);
// If we're showing instance members, don't include nested types
var namedSymbols = excludeStatic
? symbols.WhereAsArray(s => !(s.IsStatic || s is ITypeSymbol))
: (abstractsOnly ? symbols.WhereAsArray(s => s.IsAbstract) : symbols);
// if we're dotting off an instance, then add potential operators/indexers/conversions that may be
// applicable to it as well.
var unnamedSymbols = _context.IsNameOfContext || excludeInstance
? default
: GetUnnamedSymbols(originalExpression);
return new RecommendedSymbols(namedSymbols, unnamedSymbols);
}
private ImmutableArray<ISymbol> GetUnnamedSymbols(ExpressionSyntax originalExpression)
{
var semanticModel = _context.SemanticModel;
var container = GetContainerForUnnamedSymbols(semanticModel, originalExpression);
if (container == null)
return ImmutableArray<ISymbol>.Empty;
// In a case like `x?.Y` if we bind the type of `.Y` we will get a value type back (like `int`), and not
// `int?`. However, we want to think of the constructed type as that's the type of the overall expression
// that will be casted.
if (originalExpression.GetRootConditionalAccessExpression() != null)
container = TryMakeNullable(semanticModel.Compilation, container);
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var symbols);
AddIndexers(container, symbols);
AddOperators(container, symbols);
AddConversions(container, symbols);
return symbols.ToImmutable();
}
private ITypeSymbol? GetContainerForUnnamedSymbols(SemanticModel semanticModel, ExpressionSyntax originalExpression)
{
return ShouldBeTreatedAsTypeInsteadOfExpression(originalExpression, out _, out var container)
? container
: semanticModel.GetTypeInfo(originalExpression, _cancellationToken).Type;
}
private void AddIndexers(ITypeSymbol container, ArrayBuilder<ISymbol> symbols)
{
var containingType = _context.SemanticModel.GetEnclosingNamedType(_context.Position, _cancellationToken);
if (containingType == null)
return;
foreach (var member in container.RemoveNullableIfPresent().GetAccessibleMembersInThisAndBaseTypes<IPropertySymbol>(containingType))
{
if (member.IsIndexer)
symbols.Add(member);
}
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharp/Portable/Rename/CSharpRenameRewriterLanguageService.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Rename
{
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ICollection<string> _possibleNameConflicts;
private readonly Dictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ISet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new();
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new();
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.OptionSet.RenameInStrings;
_isRenamingInComments = parameters.OptionSet.RenameInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1)
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName))
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
var conflicts = ArrayBuilder<Location>.GetInstance();
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol.Kind == SymbolKind.NamedType &&
((INamedTypeSymbol)renamedSymbol).TypeKind != TypeKind.Enum)
{
var namedType = (INamedTypeSymbol)renamedSymbol;
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
}
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol &&
renamedSymbol.ContainingType.Name == renamedSymbol.Name &&
renamedSymbol.ContainingType.TypeKind != TypeKind.Enum)
{
AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(renamedSymbol.ContainingType), reverseMappedLocations);
}
if (renamedSymbol.Kind == SymbolKind.Parameter ||
renamedSymbol.Kind == SymbolKind.Local ||
renamedSymbol.Kind == SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
{
properties.Add(property);
}
}
AddConflictingParametersOfProperties(
properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.GetAncestorsOrThis(n => n.Kind() == SyntaxKind.NamespaceDeclaration).FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = ((NamespaceDeclarationSyntax)namespaceDecl).Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)token.Parent.GetAncestorsOrThis(n => n.Kind() == SyntaxKind.CompilationUnit).Single();
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
{
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
{
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutableAndFree();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.ContainsKey(location))
{
conflicts.Add(reverseMappedLocations[location]);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));
// TODO: handle Dispose for using statement and Add methods for collection initializers.
if (implicitReferencesMightConflict)
{
if (renamedSymbol.Name != renameSymbol.Name)
{
foreach (var implicitReferenceLocation in implicitReferenceLocations)
{
var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false);
switch (token.Kind())
{
case SyntaxKind.ForEachKeyword:
return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation());
case SyntaxKind.AwaitKeyword:
return ImmutableArray.Create(token.GetLocation());
}
if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft))
{
return ImmutableArray.Create(deconstructionLeft.GetLocation());
}
}
}
}
return ImmutableArray<Location>.Empty;
}
public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts(
ISymbol renamedSymbol,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
CancellationToken cancellationToken)
{
// TODO: support other implicitly used methods like dispose
if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0)
{
// TODO: partial methods currently only show the location where the rename happens as a conflict.
// Consider showing both locations as a conflict.
var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault();
if (baseType != null)
{
var implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name)
.Where(sym => !sym.Equals(renamedSymbol));
foreach (var symbol in implicitSymbols)
{
if (symbol.GetAllTypeArguments().Length != 0)
{
continue;
}
if (symbol.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)symbol;
if (symbol.Name == "MoveNext")
{
if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
else if (symbol.Name == "GetEnumerator")
{
// we are a bit pessimistic here.
// To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach
if (!method.ReturnsVoid &&
!method.Parameters.Any())
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current")
{
var property = (IPropertySymbol)symbol;
if (!property.Parameters.Any() && !property.IsWriteOnly)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
}
}
return ImmutableArray<Location>.Empty;
}
#endregion
public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts)
{
if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9)
{
var conflict = replacementText.Substring(0, replacementText.Length - 9);
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
if (symbol.Kind == SymbolKind.Property)
{
foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText })
{
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
}
// in C# we also need to add the valueText because it can be different from the text in source
// e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for
// v\u0061r and var or similar.
var valueText = replacementText;
var kind = SyntaxFacts.GetKeywordKind(replacementText);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var name = SyntaxFactory.ParseName(replacementText);
if (name.Kind() == SyntaxKind.IdentifierName)
{
valueText = ((IdentifierNameSyntax)name).Identifier.ValueText;
}
}
// this also covers the case of an escaped replacementText
if (valueText != replacementText)
{
possibleNameConflicts.Add(valueText);
}
}
/// <summary>
/// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on.
/// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
/// statement of this lambda.
/// </summary>
/// <param name="token">The token to get the complexification target for.</param>
/// <returns></returns>
public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token)
=> GetExpansionTarget(token);
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
{
// get the directly enclosing statement
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
// System.Func<int, int> myFunc = arg => X;
var possibleLambdaExpression = enclosingStatement == null
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
: null;
if (possibleLambdaExpression != null)
{
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
if (lambdaExpression.Body is ExpressionSyntax)
{
return lambdaExpression.Body;
}
}
// int M() => X;
var possibleArrowExpressionClause = enclosingStatement == null
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
: null;
if (possibleArrowExpressionClause != null)
{
return possibleArrowExpressionClause.Expression;
}
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
if (enclosingNameMemberCrefOrnull != null)
{
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
{
enclosingNameMemberCrefOrnull = null;
}
}
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
if (enclosingXmlNameAttr != null)
{
return null;
}
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
{
return enclosingInitializer.Value;
}
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
if (attributeSyntax != null)
{
return attributeSyntax;
}
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
}
#region "Helper Methods"
public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService)
{
// Identifiers we never consider valid to rename to.
switch (replacementText)
{
case "var":
case "dynamic":
case "unmanaged":
case "notnull":
return false;
}
var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal)
? replacementText : "@" + replacementText;
// Make sure we got an identifier.
if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier))
{
// We still don't have an identifier, so let's fail
return false;
}
return true;
}
/// <summary>
/// Gets the semantic model for the given node.
/// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
/// Otherwise, returns a speculative model.
/// The assumption for the later case is that span start position of the given node in it's syntax tree is same as
/// the span start of the original node in the original syntax tree.
/// </summary>
public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel)
{
if (node.SyntaxTree == originalSemanticModel.SyntaxTree)
{
// This is possible if the previous rename phase didn't rewrite any nodes in this tree.
return originalSemanticModel;
}
var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault();
if (nodeToSpeculate == null)
{
if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember))
{
nodeToSpeculate = nameMember.Name;
}
else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref))
{
nodeToSpeculate = qualifiedCref.Container;
}
else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint))
{
nodeToSpeculate = typeConstraint.Type;
}
else if (node is BaseTypeSyntax baseType)
{
nodeToSpeculate = baseType.Type;
}
else
{
return null;
}
}
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
var position = nodeToSpeculate.SpanStart;
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext);
}
#endregion
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Simplification;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Rename
{
[ExportLanguageService(typeof(IRenameRewriterLanguageService), LanguageNames.CSharp), Shared]
internal class CSharpRenameConflictLanguageService : AbstractRenameRewriterLanguageService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpRenameConflictLanguageService()
{
}
#region "Annotation"
public override SyntaxNode AnnotateAndRename(RenameRewriterParameters parameters)
{
var renameAnnotationRewriter = new RenameRewriter(parameters);
return renameAnnotationRewriter.Visit(parameters.SyntaxRoot)!;
}
private class RenameRewriter : CSharpSyntaxRewriter
{
private readonly DocumentId _documentId;
private readonly RenameAnnotation _renameRenamableSymbolDeclaration;
private readonly Solution _solution;
private readonly string _replacementText;
private readonly string _originalText;
private readonly ICollection<string> _possibleNameConflicts;
private readonly Dictionary<TextSpan, RenameLocation> _renameLocations;
private readonly ISet<TextSpan> _conflictLocations;
private readonly SemanticModel _semanticModel;
private readonly CancellationToken _cancellationToken;
private readonly ISymbol _renamedSymbol;
private readonly IAliasSymbol? _aliasSymbol;
private readonly Location? _renamableDeclarationLocation;
private readonly RenamedSpansTracker _renameSpansTracker;
private readonly bool _isVerbatim;
private readonly bool _replacementTextValid;
private readonly ISimplificationService _simplificationService;
private readonly ISemanticFactsService _semanticFactsService;
private readonly HashSet<SyntaxToken> _annotatedIdentifierTokens = new();
private readonly HashSet<InvocationExpressionSyntax> _invocationExpressionsNeedingConflictChecks = new();
private readonly AnnotationTable<RenameAnnotation> _renameAnnotations;
/// <summary>
/// Flag indicating if we should perform a rename inside string literals.
/// </summary>
private readonly bool _isRenamingInStrings;
/// <summary>
/// Flag indicating if we should perform a rename inside comment trivia.
/// </summary>
private readonly bool _isRenamingInComments;
/// <summary>
/// A map from spans of tokens needing rename within strings or comments to an optional
/// set of specific sub-spans within the token span that
/// have <see cref="_originalText"/> matches and should be renamed.
/// If this sorted set is null, it indicates that sub-spans to rename within the token span
/// are not available, and a regex match should be performed to rename
/// all <see cref="_originalText"/> matches within the span.
/// </summary>
private readonly ImmutableDictionary<TextSpan, ImmutableSortedSet<TextSpan>?> _stringAndCommentTextSpans;
public bool AnnotateForComplexification
{
get
{
return _skipRenameForComplexification > 0 && !_isProcessingComplexifiedSpans;
}
}
private int _skipRenameForComplexification;
private bool _isProcessingComplexifiedSpans;
private List<(TextSpan oldSpan, TextSpan newSpan)>? _modifiedSubSpans;
private SemanticModel? _speculativeModel;
private int _isProcessingTrivia;
private void AddModifiedSpan(TextSpan oldSpan, TextSpan newSpan)
{
newSpan = new TextSpan(oldSpan.Start, newSpan.Length);
if (!_isProcessingComplexifiedSpans)
{
_renameSpansTracker.AddModifiedSpan(_documentId, oldSpan, newSpan);
}
else
{
RoslynDebug.Assert(_modifiedSubSpans != null);
_modifiedSubSpans.Add((oldSpan, newSpan));
}
}
public RenameRewriter(RenameRewriterParameters parameters)
: base(visitIntoStructuredTrivia: true)
{
_documentId = parameters.Document.Id;
_renameRenamableSymbolDeclaration = parameters.RenamedSymbolDeclarationAnnotation;
_solution = parameters.OriginalSolution;
_replacementText = parameters.ReplacementText;
_originalText = parameters.OriginalText;
_possibleNameConflicts = parameters.PossibleNameConflicts;
_renameLocations = parameters.RenameLocations;
_conflictLocations = parameters.ConflictLocationSpans;
_cancellationToken = parameters.CancellationToken;
_semanticModel = parameters.SemanticModel;
_renamedSymbol = parameters.RenameSymbol;
_replacementTextValid = parameters.ReplacementTextValid;
_renameSpansTracker = parameters.RenameSpansTracker;
_isRenamingInStrings = parameters.OptionSet.RenameInStrings;
_isRenamingInComments = parameters.OptionSet.RenameInComments;
_stringAndCommentTextSpans = parameters.StringAndCommentTextSpans;
_renameAnnotations = parameters.RenameAnnotations;
_aliasSymbol = _renamedSymbol as IAliasSymbol;
_renamableDeclarationLocation = _renamedSymbol.Locations.FirstOrDefault(loc => loc.IsInSource && loc.SourceTree == _semanticModel.SyntaxTree);
_isVerbatim = _replacementText.StartsWith("@", StringComparison.Ordinal);
_simplificationService = parameters.Document.Project.LanguageServices.GetRequiredService<ISimplificationService>();
_semanticFactsService = parameters.Document.Project.LanguageServices.GetRequiredService<ISemanticFactsService>();
}
public override SyntaxNode? Visit(SyntaxNode? node)
{
if (node == null)
{
return node;
}
var isInConflictLambdaBody = false;
var lambdas = node.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax);
if (lambdas.Count() != 0)
{
foreach (var lambda in lambdas)
{
if (_conflictLocations.Any(cf => cf.Contains(lambda.Span)))
{
isInConflictLambdaBody = true;
break;
}
}
}
var shouldComplexifyNode = ShouldComplexifyNode(node, isInConflictLambdaBody);
SyntaxNode result;
// in case the current node was identified as being a complexification target of
// a previous node, we'll handle it accordingly.
if (shouldComplexifyNode)
{
_skipRenameForComplexification++;
result = base.Visit(node)!;
_skipRenameForComplexification--;
result = Complexify(node, result);
}
else
{
result = base.Visit(node)!;
}
return result;
}
private bool ShouldComplexifyNode(SyntaxNode node, bool isInConflictLambdaBody)
{
return !isInConflictLambdaBody &&
_skipRenameForComplexification == 0 &&
!_isProcessingComplexifiedSpans &&
_conflictLocations.Contains(node.Span) &&
(node is AttributeSyntax ||
node is AttributeArgumentSyntax ||
node is ConstructorInitializerSyntax ||
node is ExpressionSyntax ||
node is FieldDeclarationSyntax ||
node is StatementSyntax ||
node is CrefSyntax ||
node is XmlNameAttributeSyntax ||
node is TypeConstraintSyntax ||
node is BaseTypeSyntax);
}
public override SyntaxToken VisitToken(SyntaxToken token)
{
var shouldCheckTrivia = _stringAndCommentTextSpans.ContainsKey(token.Span);
_isProcessingTrivia += shouldCheckTrivia ? 1 : 0;
var newToken = base.VisitToken(token);
_isProcessingTrivia -= shouldCheckTrivia ? 1 : 0;
// Handle Alias annotations
newToken = UpdateAliasAnnotation(newToken);
// Rename matches in strings and comments
newToken = RenameWithinToken(token, newToken);
// We don't want to annotate XmlName with RenameActionAnnotation
if (newToken.Parent.IsKind(SyntaxKind.XmlName))
{
return newToken;
}
var isRenameLocation = IsRenameLocation(token);
// if this is a reference location, or the identifier token's name could possibly
// be a conflict, we need to process this token
var isOldText = token.ValueText == _originalText;
var tokenNeedsConflictCheck =
isRenameLocation ||
token.ValueText == _replacementText ||
isOldText ||
_possibleNameConflicts.Contains(token.ValueText) ||
IsPossiblyDestructorConflict(token) ||
IsPropertyAccessorNameConflict(token);
if (tokenNeedsConflictCheck)
{
newToken = RenameAndAnnotateAsync(token, newToken, isRenameLocation, isOldText).WaitAndGetResult_CanCallOnBackground(_cancellationToken);
if (!_isProcessingComplexifiedSpans)
{
_invocationExpressionsNeedingConflictChecks.AddRange(token.GetAncestors<InvocationExpressionSyntax>());
}
}
return newToken;
}
private bool IsPropertyAccessorNameConflict(SyntaxToken token)
=> IsGetPropertyAccessorNameConflict(token)
|| IsSetPropertyAccessorNameConflict(token)
|| IsInitPropertyAccessorNameConflict(token);
private bool IsGetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.GetKeyword)
&& IsNameConflictWithProperty("get", token.Parent as AccessorDeclarationSyntax);
private bool IsSetPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.SetKeyword)
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsInitPropertyAccessorNameConflict(SyntaxToken token)
=> token.IsKind(SyntaxKind.InitKeyword)
// using "set" here is intentional. The compiler generates set_PropName for both set and init accessors.
&& IsNameConflictWithProperty("set", token.Parent as AccessorDeclarationSyntax);
private bool IsNameConflictWithProperty(string prefix, AccessorDeclarationSyntax? accessor)
=> accessor?.Parent?.Parent is PropertyDeclarationSyntax property // 3 null checks in one: accessor -> accessor list -> property declaration
&& _replacementText.Equals(prefix + "_" + property.Identifier.Text, StringComparison.Ordinal);
private bool IsPossiblyDestructorConflict(SyntaxToken token)
{
return _replacementText == "Finalize" &&
token.IsKind(SyntaxKind.IdentifierToken) &&
token.Parent.IsKind(SyntaxKind.DestructorDeclaration);
}
private SyntaxNode Complexify(SyntaxNode originalNode, SyntaxNode newNode)
{
_isProcessingComplexifiedSpans = true;
_modifiedSubSpans = new List<(TextSpan oldSpan, TextSpan newSpan)>();
var annotation = new SyntaxAnnotation();
newNode = newNode.WithAdditionalAnnotations(annotation);
var speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
RoslynDebug.Assert(_speculativeModel != null, "expanding a syntax node which cannot be speculated?");
var oldSpan = originalNode.Span;
var expandParameter = originalNode.GetAncestorsOrThis(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).Count() == 0;
newNode = _simplificationService.Expand(newNode,
_speculativeModel,
annotationForReplacedAliasIdentifier: null,
expandInsideNode: null,
expandParameter: expandParameter,
cancellationToken: _cancellationToken);
speculativeTree = originalNode.SyntaxTree.GetRoot(_cancellationToken).ReplaceNode(originalNode, newNode);
newNode = speculativeTree.GetAnnotatedNodes<SyntaxNode>(annotation).First();
_speculativeModel = GetSemanticModelForNode(newNode, _semanticModel);
newNode = base.Visit(newNode)!;
var newSpan = newNode.Span;
newNode = newNode.WithoutAnnotations(annotation);
newNode = _renameAnnotations.WithAdditionalAnnotations(newNode, new RenameNodeSimplificationAnnotation() { OriginalTextSpan = oldSpan });
_renameSpansTracker.AddComplexifiedSpan(_documentId, oldSpan, new TextSpan(oldSpan.Start, newSpan.Length), _modifiedSubSpans);
_modifiedSubSpans = null;
_isProcessingComplexifiedSpans = false;
_speculativeModel = null;
return newNode;
}
private async Task<SyntaxToken> RenameAndAnnotateAsync(SyntaxToken token, SyntaxToken newToken, bool isRenameLocation, bool isOldText)
{
try
{
if (_isProcessingComplexifiedSpans)
{
// Rename Token
if (isRenameLocation)
{
var annotation = _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().FirstOrDefault();
if (annotation != null)
{
newToken = RenameToken(token, newToken, annotation.Prefix, annotation.Suffix);
AddModifiedSpan(annotation.OriginalSpan, newToken.Span);
}
else
{
newToken = RenameToken(token, newToken, prefix: null, suffix: null);
}
}
return newToken;
}
var symbols = RenameUtilities.GetSymbolsTouchingPosition(token.Span.Start, _semanticModel, _solution.Workspace, _cancellationToken);
string? suffix = null;
var prefix = isRenameLocation && _renameLocations[token.Span].IsRenamableAccessor
? newToken.ValueText.Substring(0, newToken.ValueText.IndexOf('_') + 1)
: null;
if (symbols.Length == 1)
{
var symbol = symbols[0];
if (symbol.IsConstructor())
{
symbol = symbol.ContainingSymbol;
}
var sourceDefinition = await SymbolFinder.FindSourceDefinitionAsync(symbol, _solution, _cancellationToken).ConfigureAwait(false);
symbol = sourceDefinition ?? symbol;
if (symbol is INamedTypeSymbol namedTypeSymbol)
{
if (namedTypeSymbol.IsImplicitlyDeclared &&
namedTypeSymbol.IsDelegateType() &&
namedTypeSymbol.AssociatedSymbol != null)
{
suffix = "EventHandler";
}
}
// This is a conflicting namespace declaration token. Even if the rename results in conflict with this namespace
// conflict is not shown for the namespace so we are tracking this token
if (!isRenameLocation && symbol is INamespaceSymbol && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
return newToken;
}
}
// Rename Token
if (isRenameLocation && !this.AnnotateForComplexification)
{
var oldSpan = token.Span;
newToken = RenameToken(token, newToken, prefix, suffix);
AddModifiedSpan(oldSpan, newToken.Span);
}
var renameDeclarationLocations = await
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(_solution, symbols, _cancellationToken).ConfigureAwait(false);
var isNamespaceDeclarationReference = false;
if (isRenameLocation && token.GetPreviousToken().IsKind(SyntaxKind.NamespaceKeyword))
{
isNamespaceDeclarationReference = true;
}
var isMemberGroupReference = _semanticFactsService.IsInsideNameOfExpression(_semanticModel, token.Parent, _cancellationToken);
var renameAnnotation =
new RenameActionAnnotation(
token.Span,
isRenameLocation,
prefix,
suffix,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: isOldText,
isNamespaceDeclarationReference: isNamespaceDeclarationReference,
isInvocationExpression: false,
isMemberGroupReference: isMemberGroupReference);
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, renameAnnotation, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = token.Span });
_annotatedIdentifierTokens.Add(token);
if (_renameRenamableSymbolDeclaration != null && _renamableDeclarationLocation == token.GetLocation())
{
newToken = _renameAnnotations.WithAdditionalAnnotations(newToken, _renameRenamableSymbolDeclaration);
}
return newToken;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e))
{
throw ExceptionUtilities.Unreachable;
}
}
private RenameActionAnnotation? GetAnnotationForInvocationExpression(InvocationExpressionSyntax invocationExpression)
{
var identifierToken = default(SyntaxToken);
var expressionOfInvocation = invocationExpression.Expression;
while (expressionOfInvocation != null)
{
switch (expressionOfInvocation.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
identifierToken = ((SimpleNameSyntax)expressionOfInvocation).Identifier;
break;
case SyntaxKind.SimpleMemberAccessExpression:
identifierToken = ((MemberAccessExpressionSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.QualifiedName:
identifierToken = ((QualifiedNameSyntax)expressionOfInvocation).Right.Identifier;
break;
case SyntaxKind.AliasQualifiedName:
identifierToken = ((AliasQualifiedNameSyntax)expressionOfInvocation).Name.Identifier;
break;
case SyntaxKind.ParenthesizedExpression:
expressionOfInvocation = ((ParenthesizedExpressionSyntax)expressionOfInvocation).Expression;
continue;
}
break;
}
if (identifierToken != default && !_annotatedIdentifierTokens.Contains(identifierToken))
{
var symbolInfo = _semanticModel.GetSymbolInfo(invocationExpression, _cancellationToken);
IEnumerable<ISymbol> symbols;
if (symbolInfo.Symbol == null)
{
return null;
}
else
{
symbols = SpecializedCollections.SingletonEnumerable(symbolInfo.Symbol);
}
var renameDeclarationLocations =
ConflictResolver.CreateDeclarationLocationAnnotationsAsync(
_solution,
symbols,
_cancellationToken)
.WaitAndGetResult_CanCallOnBackground(_cancellationToken);
var renameAnnotation = new RenameActionAnnotation(
identifierToken.Span,
isRenameLocation: false,
prefix: null,
suffix: null,
renameDeclarationLocations: renameDeclarationLocations,
isOriginalTextLocation: false,
isNamespaceDeclarationReference: false,
isInvocationExpression: true,
isMemberGroupReference: false);
return renameAnnotation;
}
return null;
}
public override SyntaxNode? VisitInvocationExpression(InvocationExpressionSyntax node)
{
var result = base.VisitInvocationExpression(node);
RoslynDebug.AssertNotNull(result);
if (_invocationExpressionsNeedingConflictChecks.Contains(node))
{
var renameAnnotation = GetAnnotationForInvocationExpression(node);
if (renameAnnotation != null)
{
result = _renameAnnotations.WithAdditionalAnnotations(result, renameAnnotation);
}
}
return result;
}
private bool IsRenameLocation(SyntaxToken token)
{
if (!_isProcessingComplexifiedSpans)
{
return _renameLocations.ContainsKey(token.Span);
}
else
{
RoslynDebug.Assert(_speculativeModel != null);
if (token.HasAnnotations(AliasAnnotation.Kind))
{
return false;
}
if (token.HasAnnotations(RenameAnnotation.Kind))
{
return _renameAnnotations.GetAnnotations(token).OfType<RenameActionAnnotation>().First().IsRenameLocation;
}
if (token.Parent is SimpleNameSyntax && !token.IsKind(SyntaxKind.GlobalKeyword) && token.Parent.Parent.IsKind(SyntaxKind.AliasQualifiedName, SyntaxKind.QualifiedCref, SyntaxKind.QualifiedName))
{
var symbol = _speculativeModel.GetSymbolInfo(token.Parent, _cancellationToken).Symbol;
if (symbol != null && _renamedSymbol.Kind != SymbolKind.Local && _renamedSymbol.Kind != SymbolKind.RangeVariable &&
(Equals(symbol, _renamedSymbol) || SymbolKey.GetComparer(ignoreCase: true, ignoreAssemblyKeys: false).Equals(symbol.GetSymbolKey(), _renamedSymbol.GetSymbolKey())))
{
return true;
}
}
return false;
}
}
private SyntaxToken UpdateAliasAnnotation(SyntaxToken newToken)
{
if (_aliasSymbol != null && !this.AnnotateForComplexification && newToken.HasAnnotations(AliasAnnotation.Kind))
{
newToken = RenameUtilities.UpdateAliasAnnotation(newToken, _aliasSymbol, _replacementText);
}
return newToken;
}
private SyntaxToken RenameToken(SyntaxToken oldToken, SyntaxToken newToken, string? prefix, string? suffix)
{
var parent = oldToken.Parent!;
var currentNewIdentifier = _isVerbatim ? _replacementText.Substring(1) : _replacementText;
var oldIdentifier = newToken.ValueText;
var isAttributeName = SyntaxFacts.IsAttributeName(parent);
if (isAttributeName)
{
if (oldIdentifier != _renamedSymbol.Name)
{
if (currentNewIdentifier.TryGetWithoutAttributeSuffix(out var withoutSuffix))
{
currentNewIdentifier = withoutSuffix;
}
}
}
else
{
if (!string.IsNullOrEmpty(prefix))
{
currentNewIdentifier = prefix + currentNewIdentifier;
}
if (!string.IsNullOrEmpty(suffix))
{
currentNewIdentifier += suffix;
}
}
// determine the canonical identifier name (unescaped, no unicode escaping, ...)
var valueText = currentNewIdentifier;
var kind = SyntaxFacts.GetKeywordKind(currentNewIdentifier);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var parsedIdentifier = SyntaxFactory.ParseName(currentNewIdentifier);
if (parsedIdentifier.IsKind(SyntaxKind.IdentifierName, out IdentifierNameSyntax? identifierName))
{
valueText = identifierName.Identifier.ValueText;
}
}
// TODO: we can't use escaped unicode characters in xml doc comments, so we need to pass the valuetext as text as well.
// <param name="\u... is invalid.
// if it's an attribute name we don't mess with the escaping because it might change overload resolution
newToken = _isVerbatim || (isAttributeName && oldToken.IsVerbatimIdentifier())
? newToken.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(newToken.LeadingTrivia, currentNewIdentifier, valueText, newToken.TrailingTrivia))
: newToken.CopyAnnotationsTo(SyntaxFactory.Identifier(newToken.LeadingTrivia, SyntaxKind.IdentifierToken, currentNewIdentifier, valueText, newToken.TrailingTrivia));
if (_replacementTextValid)
{
if (newToken.IsVerbatimIdentifier())
{
// a reference location should always be tried to be unescaped, whether it was escaped before rename
// or the replacement itself is escaped.
newToken = newToken.WithAdditionalAnnotations(Simplifier.Annotation);
}
else
{
newToken = CSharpSimplificationHelpers.TryEscapeIdentifierToken(newToken, parent);
}
}
return newToken;
}
private SyntaxToken RenameInStringLiteral(SyntaxToken oldToken, SyntaxToken newToken, ImmutableSortedSet<TextSpan>? subSpansToReplace, Func<SyntaxTriviaList, string, string, SyntaxTriviaList, SyntaxToken> createNewStringLiteral)
{
var originalString = newToken.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText, subSpansToReplace);
if (replacedString != originalString)
{
var oldSpan = oldToken.Span;
newToken = createNewStringLiteral(newToken.LeadingTrivia, replacedString, replacedString, newToken.TrailingTrivia);
AddModifiedSpan(oldSpan, newToken.Span);
return newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return newToken;
}
private SyntaxToken RenameInTrivia(SyntaxToken token, IEnumerable<SyntaxTrivia> leadingOrTrailingTriviaList)
{
return token.ReplaceTrivia(leadingOrTrailingTriviaList, (oldTrivia, newTrivia) =>
{
if (newTrivia.IsSingleLineComment() || newTrivia.IsMultiLineComment())
{
return RenameInCommentTrivia(newTrivia);
}
return newTrivia;
});
}
private SyntaxTrivia RenameInCommentTrivia(SyntaxTrivia trivia)
{
var originalString = trivia.ToString();
var replacedString = RenameLocations.ReferenceProcessing.ReplaceMatchingSubStrings(originalString, _originalText, _replacementText);
if (replacedString != originalString)
{
var oldSpan = trivia.Span;
var newTrivia = SyntaxFactory.Comment(replacedString);
AddModifiedSpan(oldSpan, newTrivia.Span);
return trivia.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newTrivia, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldSpan }));
}
return trivia;
}
private SyntaxToken RenameWithinToken(SyntaxToken oldToken, SyntaxToken newToken)
{
ImmutableSortedSet<TextSpan>? subSpansToReplace = null;
if (_isProcessingComplexifiedSpans ||
(_isProcessingTrivia == 0 &&
!_stringAndCommentTextSpans.TryGetValue(oldToken.Span, out subSpansToReplace)))
{
return newToken;
}
if (_isRenamingInStrings || subSpansToReplace?.Count > 0)
{
if (newToken.IsKind(SyntaxKind.StringLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.Literal);
}
else if (newToken.IsKind(SyntaxKind.InterpolatedStringTextToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, (leadingTrivia, text, value, trailingTrivia) =>
SyntaxFactory.Token(newToken.LeadingTrivia, SyntaxKind.InterpolatedStringTextToken, text, value, newToken.TrailingTrivia));
}
}
if (_isRenamingInComments)
{
if (newToken.IsKind(SyntaxKind.XmlTextLiteralToken))
{
newToken = RenameInStringLiteral(oldToken, newToken, subSpansToReplace, SyntaxFactory.XmlTextLiteral);
}
else if (newToken.IsKind(SyntaxKind.IdentifierToken) && newToken.Parent.IsKind(SyntaxKind.XmlName) && newToken.ValueText == _originalText)
{
var newIdentifierToken = SyntaxFactory.Identifier(newToken.LeadingTrivia, _replacementText, newToken.TrailingTrivia);
newToken = newToken.CopyAnnotationsTo(_renameAnnotations.WithAdditionalAnnotations(newIdentifierToken, new RenameTokenSimplificationAnnotation() { OriginalTextSpan = oldToken.Span }));
AddModifiedSpan(oldToken.Span, newToken.Span);
}
if (newToken.HasLeadingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.LeadingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithLeadingTrivia(updatedToken.LeadingTrivia);
}
}
if (newToken.HasTrailingTrivia)
{
var updatedToken = RenameInTrivia(oldToken, oldToken.TrailingTrivia);
if (updatedToken != oldToken)
{
newToken = newToken.WithTrailingTrivia(updatedToken.TrailingTrivia);
}
}
}
return newToken;
}
}
#endregion
#region "Declaration Conflicts"
public override bool LocalVariableConflict(
SyntaxToken token,
IEnumerable<ISymbol> newReferencedSymbols)
{
if (token.Parent.IsKind(SyntaxKind.IdentifierName, out ExpressionSyntax? expression) &&
token.Parent.IsParentKind(SyntaxKind.InvocationExpression) &&
token.GetPreviousToken().Kind() != SyntaxKind.DotToken &&
token.GetNextToken().Kind() != SyntaxKind.DotToken)
{
var enclosingMemberDeclaration = expression.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (enclosingMemberDeclaration != null)
{
var locals = enclosingMemberDeclaration.GetLocalDeclarationMap()[token.ValueText];
if (locals.Length > 0)
{
// This unqualified invocation name matches the name of an existing local
// or parameter. Report a conflict if the matching local/parameter is not
// a delegate type.
var relevantLocals = newReferencedSymbols
.Where(s => s.MatchesKind(SymbolKind.Local, SymbolKind.Parameter) && s.Name == token.ValueText);
if (relevantLocals.Count() != 1)
{
return true;
}
var matchingLocal = relevantLocals.Single();
var invocationTargetsLocalOfDelegateType =
(matchingLocal.IsKind(SymbolKind.Local) && ((ILocalSymbol)matchingLocal).Type.IsDelegateType()) ||
(matchingLocal.IsKind(SymbolKind.Parameter) && ((IParameterSymbol)matchingLocal).Type.IsDelegateType());
return !invocationTargetsLocalOfDelegateType;
}
}
}
return false;
}
public override async Task<ImmutableArray<Location>> ComputeDeclarationConflictsAsync(
string replacementText,
ISymbol renamedSymbol,
ISymbol renameSymbol,
IEnumerable<ISymbol> referencedSymbols,
Solution baseSolution,
Solution newSolution,
IDictionary<Location, Location> reverseMappedLocations,
CancellationToken cancellationToken)
{
try
{
using var _ = ArrayBuilder<Location>.GetInstance(out var conflicts);
// If we're renaming a named type, we can conflict with members w/ our same name. Note:
// this doesn't apply to enums.
if (renamedSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } namedType)
AddSymbolSourceSpans(conflicts, namedType.GetMembers(renamedSymbol.Name), reverseMappedLocations);
// If we're contained in a named type (we may be a named type ourself!) then we have a
// conflict. NOTE(cyrusn): This does not apply to enums.
if (renamedSymbol.ContainingSymbol is INamedTypeSymbol { TypeKind: not TypeKind.Enum } containingNamedType &&
containingNamedType.Name == renamedSymbol.Name)
{
AddSymbolSourceSpans(conflicts, SpecializedCollections.SingletonEnumerable(containingNamedType), reverseMappedLocations);
}
if (renamedSymbol.Kind == SymbolKind.Parameter ||
renamedSymbol.Kind == SymbolKind.Local ||
renamedSymbol.Kind == SymbolKind.RangeVariable)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
// If this is a parameter symbol for a partial method definition, be sure we visited
// the implementation part's body.
if (renamedSymbol is IParameterSymbol renamedParameterSymbol &&
renamedSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
methodSymbol.PartialImplementationPart != null)
{
var matchingParameterSymbol = methodSymbol.PartialImplementationPart.Parameters[renamedParameterSymbol.Ordinal];
token = matchingParameterSymbol.Locations.Single().FindToken(cancellationToken);
memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
visitor = new LocalConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
}
else if (renamedSymbol.Kind == SymbolKind.Label)
{
var token = renamedSymbol.Locations.Single().FindToken(cancellationToken);
var memberDeclaration = token.GetAncestor<MemberDeclarationSyntax>();
var visitor = new LabelConflictVisitor(token);
visitor.Visit(memberDeclaration);
conflicts.AddRange(visitor.ConflictingTokens.Select(t => reverseMappedLocations[t.GetLocation()]));
}
else if (renamedSymbol.Kind == SymbolKind.Method)
{
conflicts.AddRange(DeclarationConflictHelpers.GetMembersWithConflictingSignatures((IMethodSymbol)renamedSymbol, trimOptionalParameters: false).Select(t => reverseMappedLocations[t]));
// we allow renaming overrides of VB property accessors with parameters in C#.
// VB has a special rule that properties are not allowed to have the same name as any of the parameters.
// Because this declaration in C# affects the property declaration in VB, we need to check this VB rule here in C#.
var properties = new List<ISymbol>();
foreach (var referencedSymbol in referencedSymbols)
{
var property = await RenameLocations.ReferenceProcessing.TryGetPropertyFromAccessorOrAnOverrideAsync(
referencedSymbol, baseSolution, cancellationToken).ConfigureAwait(false);
if (property != null)
properties.Add(property);
}
AddConflictingParametersOfProperties(properties.Distinct(), replacementText, conflicts);
}
else if (renamedSymbol.Kind == SymbolKind.Alias)
{
// in C# there can only be one using with the same alias name in the same block (top of file of namespace).
// It's ok to redefine the alias in different blocks.
var location = renamedSymbol.Locations.Single();
var tree = location.SourceTree;
Contract.ThrowIfNull(tree);
var token = await tree.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentUsing = (UsingDirectiveSyntax)token.Parent!.Parent!.Parent!;
var namespaceDecl = token.Parent.Ancestors().OfType<BaseNamespaceDeclarationSyntax>().FirstOrDefault();
SyntaxList<UsingDirectiveSyntax> usings;
if (namespaceDecl != null)
{
usings = namespaceDecl.Usings;
}
else
{
var compilationUnit = (CompilationUnitSyntax)await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
usings = compilationUnit.Usings;
}
foreach (var usingDirective in usings)
{
if (usingDirective.Alias != null && usingDirective != currentUsing)
{
if (usingDirective.Alias.Name.Identifier.ValueText == currentUsing.Alias!.Name.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[usingDirective.Alias.Name.GetLocation()]);
}
}
}
else if (renamedSymbol.Kind == SymbolKind.TypeParameter)
{
foreach (var location in renamedSymbol.Locations)
{
var token = await location.SourceTree!.GetTouchingTokenAsync(location.SourceSpan.Start, cancellationToken, findInsideTrivia: true).ConfigureAwait(false);
var currentTypeParameter = token.Parent!;
foreach (var typeParameter in ((TypeParameterListSyntax)currentTypeParameter.Parent!).Parameters)
{
if (typeParameter != currentTypeParameter && token.ValueText == typeParameter.Identifier.ValueText)
conflicts.Add(reverseMappedLocations[typeParameter.Identifier.GetLocation()]);
}
}
}
// if the renamed symbol is a type member, it's name should not conflict with a type parameter
if (renamedSymbol.ContainingType != null && renamedSymbol.ContainingType.GetMembers(renamedSymbol.Name).Contains(renamedSymbol))
{
var conflictingLocations = renamedSymbol.ContainingType.TypeParameters
.Where(t => t.Name == renamedSymbol.Name)
.SelectMany(t => t.Locations);
foreach (var location in conflictingLocations)
{
var typeParameterToken = location.FindToken(cancellationToken);
conflicts.Add(reverseMappedLocations[typeParameterToken.GetLocation()]);
}
}
return conflicts.ToImmutable();
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static async Task<ISymbol?> GetVBPropertyFromAccessorOrAnOverrideAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
try
{
if (symbol.IsPropertyAccessor())
{
var property = ((IMethodSymbol)symbol).AssociatedSymbol!;
return property.Language == LanguageNames.VisualBasic ? property : null;
}
if (symbol.IsOverride && symbol.GetOverriddenMember() != null)
{
var originalSourceSymbol = await SymbolFinder.FindSourceDefinitionAsync(symbol.GetOverriddenMember(), solution, cancellationToken).ConfigureAwait(false);
if (originalSourceSymbol != null)
{
return await GetVBPropertyFromAccessorOrAnOverrideAsync(originalSourceSymbol, solution, cancellationToken).ConfigureAwait(false);
}
}
return null;
}
catch (Exception e) when (FatalError.ReportAndPropagateUnlessCanceled(e, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
private static void AddSymbolSourceSpans(
ArrayBuilder<Location> conflicts, IEnumerable<ISymbol> symbols,
IDictionary<Location, Location> reverseMappedLocations)
{
foreach (var symbol in symbols)
{
foreach (var location in symbol.Locations)
{
// reverseMappedLocations may not contain the location if the location's token
// does not contain the text of it's name (e.g. the getter of "int X { get; }"
// does not contain the text "get_X" so conflicting renames to "get_X" will not
// have added the getter to reverseMappedLocations).
if (location.IsInSource && reverseMappedLocations.ContainsKey(location))
{
conflicts.Add(reverseMappedLocations[location]);
}
}
}
}
public override async Task<ImmutableArray<Location>> ComputeImplicitReferenceConflictsAsync(
ISymbol renameSymbol, ISymbol renamedSymbol, IEnumerable<ReferenceLocation> implicitReferenceLocations, CancellationToken cancellationToken)
{
// Handle renaming of symbols used for foreach
var implicitReferencesMightConflict = renameSymbol.Kind == SymbolKind.Property &&
string.Compare(renameSymbol.Name, "Current", StringComparison.OrdinalIgnoreCase) == 0;
implicitReferencesMightConflict =
implicitReferencesMightConflict ||
(renameSymbol.Kind == SymbolKind.Method &&
(string.Compare(renameSymbol.Name, WellKnownMemberNames.MoveNextMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetEnumeratorMethodName, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.GetAwaiter, StringComparison.OrdinalIgnoreCase) == 0 ||
string.Compare(renameSymbol.Name, WellKnownMemberNames.DeconstructMethodName, StringComparison.OrdinalIgnoreCase) == 0));
// TODO: handle Dispose for using statement and Add methods for collection initializers.
if (implicitReferencesMightConflict)
{
if (renamedSymbol.Name != renameSymbol.Name)
{
foreach (var implicitReferenceLocation in implicitReferenceLocations)
{
var token = await implicitReferenceLocation.Location.SourceTree!.GetTouchingTokenAsync(
implicitReferenceLocation.Location.SourceSpan.Start, cancellationToken, findInsideTrivia: false).ConfigureAwait(false);
switch (token.Kind())
{
case SyntaxKind.ForEachKeyword:
return ImmutableArray.Create(((CommonForEachStatementSyntax)token.Parent!).Expression.GetLocation());
case SyntaxKind.AwaitKeyword:
return ImmutableArray.Create(token.GetLocation());
}
if (token.Parent.IsInDeconstructionLeft(out var deconstructionLeft))
{
return ImmutableArray.Create(deconstructionLeft.GetLocation());
}
}
}
}
return ImmutableArray<Location>.Empty;
}
public override ImmutableArray<Location> ComputePossibleImplicitUsageConflicts(
ISymbol renamedSymbol,
SemanticModel semanticModel,
Location originalDeclarationLocation,
int newDeclarationLocationStartingPosition,
CancellationToken cancellationToken)
{
// TODO: support other implicitly used methods like dispose
if ((renamedSymbol.Name == "MoveNext" || renamedSymbol.Name == "GetEnumerator" || renamedSymbol.Name == "Current") && renamedSymbol.GetAllTypeArguments().Length == 0)
{
// TODO: partial methods currently only show the location where the rename happens as a conflict.
// Consider showing both locations as a conflict.
var baseType = renamedSymbol.ContainingType?.GetBaseTypes().FirstOrDefault();
if (baseType != null)
{
var implicitSymbols = semanticModel.LookupSymbols(
newDeclarationLocationStartingPosition,
baseType,
renamedSymbol.Name)
.Where(sym => !sym.Equals(renamedSymbol));
foreach (var symbol in implicitSymbols)
{
if (symbol.GetAllTypeArguments().Length != 0)
{
continue;
}
if (symbol.Kind == SymbolKind.Method)
{
var method = (IMethodSymbol)symbol;
if (symbol.Name == "MoveNext")
{
if (!method.ReturnsVoid && !method.Parameters.Any() && method.ReturnType.SpecialType == SpecialType.System_Boolean)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
else if (symbol.Name == "GetEnumerator")
{
// we are a bit pessimistic here.
// To be sure we would need to check if the returned type is having a MoveNext and Current as required by foreach
if (!method.ReturnsVoid &&
!method.Parameters.Any())
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
else if (symbol.Kind == SymbolKind.Property && symbol.Name == "Current")
{
var property = (IPropertySymbol)symbol;
if (!property.Parameters.Any() && !property.IsWriteOnly)
{
return ImmutableArray.Create(originalDeclarationLocation);
}
}
}
}
}
return ImmutableArray<Location>.Empty;
}
#endregion
public override void TryAddPossibleNameConflicts(ISymbol symbol, string replacementText, ICollection<string> possibleNameConflicts)
{
if (replacementText.EndsWith("Attribute", StringComparison.Ordinal) && replacementText.Length > 9)
{
var conflict = replacementText.Substring(0, replacementText.Length - 9);
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
if (symbol.Kind == SymbolKind.Property)
{
foreach (var conflict in new string[] { "_" + replacementText, "get_" + replacementText, "set_" + replacementText })
{
if (!possibleNameConflicts.Contains(conflict))
{
possibleNameConflicts.Add(conflict);
}
}
}
// in C# we also need to add the valueText because it can be different from the text in source
// e.g. it can contain escaped unicode characters. Otherwise conflicts would be detected for
// v\u0061r and var or similar.
var valueText = replacementText;
var kind = SyntaxFacts.GetKeywordKind(replacementText);
if (kind != SyntaxKind.None)
{
valueText = SyntaxFacts.GetText(kind);
}
else
{
var name = SyntaxFactory.ParseName(replacementText);
if (name.Kind() == SyntaxKind.IdentifierName)
{
valueText = ((IdentifierNameSyntax)name).Identifier.ValueText;
}
}
// this also covers the case of an escaped replacementText
if (valueText != replacementText)
{
possibleNameConflicts.Add(valueText);
}
}
/// <summary>
/// Gets the top most enclosing statement or CrefSyntax as target to call MakeExplicit on.
/// It's either the enclosing statement, or if this statement is inside of a lambda expression, the enclosing
/// statement of this lambda.
/// </summary>
/// <param name="token">The token to get the complexification target for.</param>
/// <returns></returns>
public override SyntaxNode? GetExpansionTargetForLocation(SyntaxToken token)
=> GetExpansionTarget(token);
private static SyntaxNode? GetExpansionTarget(SyntaxToken token)
{
// get the directly enclosing statement
var enclosingStatement = token.GetAncestors(n => n is StatementSyntax).FirstOrDefault();
// System.Func<int, int> myFunc = arg => X;
var possibleLambdaExpression = enclosingStatement == null
? token.GetAncestors(n => n is SimpleLambdaExpressionSyntax || n is ParenthesizedLambdaExpressionSyntax).FirstOrDefault()
: null;
if (possibleLambdaExpression != null)
{
var lambdaExpression = ((LambdaExpressionSyntax)possibleLambdaExpression);
if (lambdaExpression.Body is ExpressionSyntax)
{
return lambdaExpression.Body;
}
}
// int M() => X;
var possibleArrowExpressionClause = enclosingStatement == null
? token.GetAncestors<ArrowExpressionClauseSyntax>().FirstOrDefault()
: null;
if (possibleArrowExpressionClause != null)
{
return possibleArrowExpressionClause.Expression;
}
var enclosingNameMemberCrefOrnull = token.GetAncestors(n => n is NameMemberCrefSyntax).LastOrDefault();
if (enclosingNameMemberCrefOrnull != null)
{
if (token.Parent is TypeSyntax && token.Parent.Parent is TypeSyntax)
{
enclosingNameMemberCrefOrnull = null;
}
}
var enclosingXmlNameAttr = token.GetAncestors(n => n is XmlNameAttributeSyntax).FirstOrDefault();
if (enclosingXmlNameAttr != null)
{
return null;
}
var enclosingInitializer = token.GetAncestors<EqualsValueClauseSyntax>().FirstOrDefault();
if (enclosingStatement == null && enclosingInitializer != null && enclosingInitializer.Parent is VariableDeclaratorSyntax)
{
return enclosingInitializer.Value;
}
var attributeSyntax = token.GetAncestor<AttributeSyntax>();
if (attributeSyntax != null)
{
return attributeSyntax;
}
// there seems to be no statement above this one. Let's see if we can at least get an SimpleNameSyntax
return enclosingStatement ?? enclosingNameMemberCrefOrnull ?? token.GetAncestors(n => n is SimpleNameSyntax).FirstOrDefault();
}
#region "Helper Methods"
public override bool IsIdentifierValid(string replacementText, ISyntaxFactsService syntaxFactsService)
{
// Identifiers we never consider valid to rename to.
switch (replacementText)
{
case "var":
case "dynamic":
case "unmanaged":
case "notnull":
return false;
}
var escapedIdentifier = replacementText.StartsWith("@", StringComparison.Ordinal)
? replacementText : "@" + replacementText;
// Make sure we got an identifier.
if (!syntaxFactsService.IsValidIdentifier(escapedIdentifier))
{
// We still don't have an identifier, so let's fail
return false;
}
return true;
}
/// <summary>
/// Gets the semantic model for the given node.
/// If the node belongs to the syntax tree of the original semantic model, then returns originalSemanticModel.
/// Otherwise, returns a speculative model.
/// The assumption for the later case is that span start position of the given node in it's syntax tree is same as
/// the span start of the original node in the original syntax tree.
/// </summary>
public static SemanticModel? GetSemanticModelForNode(SyntaxNode node, SemanticModel originalSemanticModel)
{
if (node.SyntaxTree == originalSemanticModel.SyntaxTree)
{
// This is possible if the previous rename phase didn't rewrite any nodes in this tree.
return originalSemanticModel;
}
var nodeToSpeculate = node.GetAncestorsOrThis(n => SpeculationAnalyzer.CanSpeculateOnNode(n)).LastOrDefault();
if (nodeToSpeculate == null)
{
if (node.IsKind(SyntaxKind.NameMemberCref, out NameMemberCrefSyntax? nameMember))
{
nodeToSpeculate = nameMember.Name;
}
else if (node.IsKind(SyntaxKind.QualifiedCref, out QualifiedCrefSyntax? qualifiedCref))
{
nodeToSpeculate = qualifiedCref.Container;
}
else if (node.IsKind(SyntaxKind.TypeConstraint, out TypeConstraintSyntax? typeConstraint))
{
nodeToSpeculate = typeConstraint.Type;
}
else if (node is BaseTypeSyntax baseType)
{
nodeToSpeculate = baseType.Type;
}
else
{
return null;
}
}
var isInNamespaceOrTypeContext = SyntaxFacts.IsInNamespaceOrTypeContext(node as ExpressionSyntax);
var position = nodeToSpeculate.SpanStart;
return SpeculationAnalyzer.CreateSpeculativeSemanticModelForNode(nodeToSpeculate, originalSemanticModel, position, isInNamespaceOrTypeContext);
}
#endregion
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/CSharpTest/OrganizeImports/OrganizeUsingsTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports
{
[UseExportProvider]
public class OrganizeUsingsTests
{
protected static async Task CheckAsync(
string initial, string final,
bool placeSystemNamespaceFirst = false,
bool separateImportGroups = false)
{
using var workspace = new AdhocWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var document = project.AddDocument("Document", initial.NormalizeLineEndings());
var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst);
newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups);
document = document.WithSolutionOptions(newOptions);
var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default);
Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task EmptyFile()
=> await CheckAsync(string.Empty, string.Empty);
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SingleUsingStatement()
{
var initial = @"using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AliasesAtBottom()
{
var initial =
@"using A = B;
using C;
using D = E;
using F;";
var final =
@"using C;
using F;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task UsingStaticsBetweenUsingsAndAliases()
{
var initial =
@"using static System.Convert;
using A = B;
using C;
using Z;
using D = E;
using static System.Console;
using F;";
var final =
@"using C;
using F;
using Z;
using static System.Console;
using static System.Convert;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedStatements()
{
var initial =
@"using B;
using A;
namespace N
{
using D;
using C;
namespace N1
{
using F;
using E;
}
namespace N2
{
using H;
using G;
}
}
namespace N3
{
using J;
using I;
namespace N4
{
using L;
using K;
}
namespace N5
{
using N;
using M;
}
}";
var final =
@"using A;
using B;
namespace N
{
using C;
using D;
namespace N1
{
using E;
using F;
}
namespace N2
{
using G;
using H;
}
}
namespace N3
{
using I;
using J;
namespace N4
{
using K;
using L;
}
namespace N5
{
using M;
using N;
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task FileScopedNamespace()
{
var initial =
@"using B;
using A;
namespace N;
using D;
using C;
";
var final =
@"using A;
using B;
namespace N;
using C;
using D;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystemWithUsingStatic()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
using static System.BitConverter;
using static Microsoft.Win32.Registry;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystemWithUsingStatics()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IndentationAfterSorting()
{
var initial =
@"namespace A
{
using V.W;
using U;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
var final =
@"namespace A
{
using U;
using V.W;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile3()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile4()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile5()
{
var initial =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile3()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// I like namespace A
using A;
/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile1()
{
var initial =
@"namespace N
{
// attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// attached to System
using System;
// attached to System.Text
using System.Text;
}";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile2()
{
var initial =
@"namespace N
{
// not attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// not attached to System.Text
// attached to System
using System;
using System.Text;
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSortIfEndIfBlocks()
{
var initial =
@"using D;
#if MYCONFIG
using C;
#else
using B;
#endif
using A;
namespace A { }
namespace B { }
namespace C { }
namespace D { }";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task ExternAliases()
{
var initial =
@"extern alias Z;
extern alias Y;
extern alias X;
using C;
using U = C.L.T;
using O = A.J;
using A;
using W = A.J.R;
using N = B.K;
using V = B.K.S;
using M = C.L;
using B;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
var final =
@"extern alias X;
extern alias Y;
extern alias Z;
using A;
using B;
using C;
using M = C.L;
using N = B.K;
using O = A.J;
using U = C.L.T;
using V = B.K.S;
using W = A.J.R;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DuplicateUsings()
{
var initial =
@"using A;
using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InlineComments()
{
var initial =
@"/*00*/using/*01*/D/*02*/;/*03*/
/*04*/using/*05*/C/*06*/;/*07*/
/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*16*/";
var final =
@"/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*04*/using/*05*/C/*06*/;/*07*/
/*00*/using/*01*/D/*02*/;/*03*/
/*16*/";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AllOnOneLine()
{
var initial =
@"using C; using B; using A;";
var final =
@"using A;
using B;
using C; ";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideRegionBlock()
{
var initial =
@"#region Using directives
using C;
using A;
using B;
#endregion
class Class1
{
}";
var final =
@"#region Using directives
using A;
using B;
using C;
#endregion
class Class1
{
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedRegionBlock()
{
var initial =
@"using C;
#region Z
using A;
#endregion
using B;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task MultipleRegionBlocks()
{
var initial =
@"#region Using directives
using C;
#region Z
using A;
#endregion
using B;
#endregion";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InterleavedNewlines()
{
var initial =
@"using B;
using A;
using C;
class D { }";
var final =
@"using A;
using B;
using C;
class D { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideIfEndIfBlock()
{
var initial =
@"#if !X
using B;
using A;
using C;
#endif";
var final =
@"#if !X
using A;
using B;
using C;
#endif";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockAbove()
{
var initial =
@"#if !X
using C;
using B;
using F;
#endif
using D;
using A;
using E;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockMiddle()
{
var initial =
@"using D;
using A;
using H;
#if !X
using C;
using B;
using I;
#endif
using F;
using E;
using G;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockBelow()
{
var initial =
@"using D;
using A;
using E;
#if !X
using C;
using B;
using F;
#endif";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task Korean()
{
var initial =
@"using ํ;
using ํ;
using ํ;
using ์นด;
using ์ฐจ;
using ์;
using ์;
using ์ฌ;
using ๋ฐ;
using ๋ง;
using ๋ผ;
using ๋ค;
using ๋;
using ๊ฐ;";
var final =
@"using ๊ฐ;
using ๋;
using ๋ค;
using ๋ผ;
using ๋ง;
using ๋ฐ;
using ์ฌ;
using ์;
using ์;
using ์ฐจ;
using ์นด;
using ํ;
using ํ;
using ํ;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem1()
{
var initial =
@"using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using D.System;
using System;
using System.Collections;
using A;";
var final =
@"using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem2()
{
var initial =
@"extern alias S;
extern alias R;
extern alias T;
using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using Y = System.UInt32;
using Z = System.Int32;
using D.System;
using System;
using N = System;
using M = System.Collections;
using System.Collections;
using A;";
var final =
@"extern alias R;
extern alias S;
extern alias T;
using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
using M = System.Collections;
using N = System;
using Y = System.UInt32;
using Z = System.Int32;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity1()
{
var initial =
@"using Bb;
using B;
using bB;
using b;
using Aa;
using a;
using A;
using aa;
using aA;
using AA;
using bb;
using BB;
using bBb;
using bbB;
using ใ;
using ใข;
using ๏ฝฑ;
using ใใ;
using ใใข;
using ใ๏ฝฑ;
using ใขใ;
using cC;
using Cc;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;
using BBb;
using BbB;
using bBB;
using BBB;
using c;
using C;
using bbb;
using Bbb;
using cc;
using cC;
using CC;
// If Kana is sensitive ใ != ใข, if Kana is insensitive ใ == ใข.
// If Width is sensitiveใข != ๏ฝฑ, if Width is insensitive ใข == ๏ฝฑ.";
var final =
@"using a;
using A;
using aa;
using aA;
using Aa;
using AA;
using b;
using B;
using bb;
using bB;
using Bb;
using BB;
using bbb;
using bbB;
using bBb;
using bBB;
using Bbb;
using BbB;
using BBb;
using BBB;
using c;
using C;
using cc;
using cC;
using cC;
using Cc;
using CC;
using ใข;
using ๏ฝฑ;
using ใ;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;
using ใขใ;
using ๏ฝฑใ;
using ใใข;
using ใ๏ฝฑ;
using ใใ;
// If Kana is sensitive ใ != ใข, if Kana is insensitive ใ == ใข.
// If Width is sensitiveใข != ๏ฝฑ, if Width is insensitive ใข == ๏ฝฑ.";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity2()
{
var initial =
@"using ใ;
using ใข;
using ๏ฝฑ;
using ใใ;
using ใใข;
using ใ๏ฝฑ;
using ใขใ;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;";
var final =
@"using ใข;
using ๏ฝฑ;
using ใ;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;
using ใขใ;
using ๏ฝฑใ;
using ใใข;
using ใ๏ฝฑ;
using ใใ;
";
await CheckAsync(initial, final);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping()
{
var initial =
@"// Banner
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using IntList = System.Collections.Generic.List<int>;
using static System.Console;";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping2()
{
// Make sure we don't insert extra newlines if they're already there.
var initial =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: 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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Workspaces.UnitTests.OrganizeImports
{
[UseExportProvider]
public class OrganizeUsingsTests
{
protected static async Task CheckAsync(
string initial, string final,
bool placeSystemNamespaceFirst = false,
bool separateImportGroups = false)
{
using var workspace = new AdhocWorkspace();
var project = workspace.CurrentSolution.AddProject("Project", "Project.dll", LanguageNames.CSharp);
var document = project.AddDocument("Document", initial.NormalizeLineEndings());
var newOptions = workspace.Options.WithChangedOption(new OptionKey(GenerationOptions.PlaceSystemNamespaceFirst, document.Project.Language), placeSystemNamespaceFirst);
newOptions = newOptions.WithChangedOption(new OptionKey(GenerationOptions.SeparateImportDirectiveGroups, document.Project.Language), separateImportGroups);
document = document.WithSolutionOptions(newOptions);
var newRoot = await (await Formatter.OrganizeImportsAsync(document, CancellationToken.None)).GetRequiredSyntaxRootAsync(default);
Assert.Equal(final.NormalizeLineEndings(), newRoot.ToFullString());
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task EmptyFile()
=> await CheckAsync(string.Empty, string.Empty);
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SingleUsingStatement()
{
var initial = @"using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AliasesAtBottom()
{
var initial =
@"using A = B;
using C;
using D = E;
using F;";
var final =
@"using C;
using F;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task UsingStaticsBetweenUsingsAndAliases()
{
var initial =
@"using static System.Convert;
using A = B;
using C;
using Z;
using D = E;
using static System.Console;
using F;";
var final =
@"using C;
using F;
using Z;
using static System.Console;
using static System.Convert;
using A = B;
using D = E;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedStatements()
{
var initial =
@"using B;
using A;
namespace N
{
using D;
using C;
namespace N1
{
using F;
using E;
}
namespace N2
{
using H;
using G;
}
}
namespace N3
{
using J;
using I;
namespace N4
{
using L;
using K;
}
namespace N5
{
using N;
using M;
}
}";
var final =
@"using A;
using B;
namespace N
{
using C;
using D;
namespace N1
{
using E;
using F;
}
namespace N2
{
using G;
using H;
}
}
namespace N3
{
using I;
using J;
namespace N4
{
using K;
using L;
}
namespace N5
{
using M;
using N;
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task FileScopedNamespace()
{
var initial =
@"using B;
using A;
namespace N;
using D;
using C;
";
var final =
@"using A;
using B;
namespace N;
using C;
using D;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task SpecialCaseSystemWithUsingStatic()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using System;
using System.Linq;
using M1;
using M2;
using static System.BitConverter;
using static Microsoft.Win32.Registry;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystemWithUsingStatics()
{
var initial =
@"using M2;
using M1;
using System.Linq;
using System;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
var final =
@"using M1;
using M2;
using System;
using System.Linq;
using static Microsoft.Win32.Registry;
using static System.BitConverter;";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IndentationAfterSorting()
{
var initial =
@"namespace A
{
using V.W;
using U;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
var final =
@"namespace A
{
using U;
using V.W;
using X.Y.Z;
class B { }
}
namespace U { }
namespace V.W { }
namespace X.Y.Z { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotTouchCommentsAtBeginningOfFile3()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile4()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
[WorkItem(33251, "https://github.com/dotnet/roslyn/issues/33251")]
public async Task DoNotTouchCommentsAtBeginningOfFile5()
{
var initial =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/** Copyright (c) Microsoft Corporation. All rights reserved.
*/
/// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile1()
{
var initial =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"// Copyright (c) Microsoft Corporation. All rights reserved.
// I like namespace A
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile2()
{
var initial =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
using B;
/* I like namespace A */
using A;
namespace A { }
namespace B { }";
var final =
@"/* Copyright (c) Microsoft Corporation. All rights reserved. */
/* I like namespace A */
using A;
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoTouchCommentsAtBeginningOfFile3()
{
var initial =
@"/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
/// I like namespace A
using A;
namespace A { }
namespace B { }";
var final =
@"/// I like namespace A
using A;
/// Copyright (c) Microsoft Corporation. All rights reserved.
using B;
namespace A { }
namespace B { }";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile1()
{
var initial =
@"namespace N
{
// attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// attached to System
using System;
// attached to System.Text
using System.Text;
}";
await CheckAsync(initial, final);
}
[WorkItem(2480, "https://github.com/dotnet/roslyn/issues/2480")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CommentsNotAtTheStartOfTheFile2()
{
var initial =
@"namespace N
{
// not attached to System.Text
using System.Text;
// attached to System
using System;
}";
var final =
@"namespace N
{
// not attached to System.Text
// attached to System
using System;
using System.Text;
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSortIfEndIfBlocks()
{
var initial =
@"using D;
#if MYCONFIG
using C;
#else
using B;
#endif
using A;
namespace A { }
namespace B { }
namespace C { }
namespace D { }";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task ExternAliases()
{
var initial =
@"extern alias Z;
extern alias Y;
extern alias X;
using C;
using U = C.L.T;
using O = A.J;
using A;
using W = A.J.R;
using N = B.K;
using V = B.K.S;
using M = C.L;
using B;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
var final =
@"extern alias X;
extern alias Y;
extern alias Z;
using A;
using B;
using C;
using M = C.L;
using N = B.K;
using O = A.J;
using U = C.L.T;
using V = B.K.S;
using W = A.J.R;
namespace A
{
namespace J
{
class R { }
}
}
namespace B
{
namespace K
{
struct S { }
}
}
namespace C
{
namespace L
{
struct T { }
}
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DuplicateUsings()
{
var initial =
@"using A;
using A;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InlineComments()
{
var initial =
@"/*00*/using/*01*/D/*02*/;/*03*/
/*04*/using/*05*/C/*06*/;/*07*/
/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*16*/";
var final =
@"/*08*/using/*09*/A/*10*/;/*11*/
/*12*/using/*13*/B/*14*/;/*15*/
/*04*/using/*05*/C/*06*/;/*07*/
/*00*/using/*01*/D/*02*/;/*03*/
/*16*/";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task AllOnOneLine()
{
var initial =
@"using C; using B; using A;";
var final =
@"using A;
using B;
using C; ";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideRegionBlock()
{
var initial =
@"#region Using directives
using C;
using A;
using B;
#endregion
class Class1
{
}";
var final =
@"#region Using directives
using A;
using B;
using C;
#endregion
class Class1
{
}";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task NestedRegionBlock()
{
var initial =
@"using C;
#region Z
using A;
#endregion
using B;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task MultipleRegionBlocks()
{
var initial =
@"#region Using directives
using C;
#region Z
using A;
#endregion
using B;
#endregion";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InterleavedNewlines()
{
var initial =
@"using B;
using A;
using C;
class D { }";
var final =
@"using A;
using B;
using C;
class D { }";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task InsideIfEndIfBlock()
{
var initial =
@"#if !X
using B;
using A;
using C;
#endif";
var final =
@"#if !X
using A;
using B;
using C;
#endif";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockAbove()
{
var initial =
@"#if !X
using C;
using B;
using F;
#endif
using D;
using A;
using E;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockMiddle()
{
var initial =
@"using D;
using A;
using H;
#if !X
using C;
using B;
using I;
#endif
using F;
using E;
using G;";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task IfEndIfBlockBelow()
{
var initial =
@"using D;
using A;
using E;
#if !X
using C;
using B;
using F;
#endif";
var final = initial;
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task Korean()
{
var initial =
@"using ํ;
using ํ;
using ํ;
using ์นด;
using ์ฐจ;
using ์;
using ์;
using ์ฌ;
using ๋ฐ;
using ๋ง;
using ๋ผ;
using ๋ค;
using ๋;
using ๊ฐ;";
var final =
@"using ๊ฐ;
using ๋;
using ๋ค;
using ๋ผ;
using ๋ง;
using ๋ฐ;
using ์ฌ;
using ์;
using ์;
using ์ฐจ;
using ์นด;
using ํ;
using ํ;
using ํ;
";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem1()
{
var initial =
@"using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using D.System;
using System;
using System.Collections;
using A;";
var final =
@"using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task DoNotSpecialCaseSystem2()
{
var initial =
@"extern alias S;
extern alias R;
extern alias T;
using B;
using System.Collections.Generic;
using C;
using _System;
using SystemZ;
using Y = System.UInt32;
using Z = System.Int32;
using D.System;
using System;
using N = System;
using M = System.Collections;
using System.Collections;
using A;";
var final =
@"extern alias R;
extern alias S;
extern alias T;
using _System;
using A;
using B;
using C;
using D.System;
using System;
using System.Collections;
using System.Collections.Generic;
using SystemZ;
using M = System.Collections;
using N = System;
using Y = System.UInt32;
using Z = System.Int32;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: false);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity1()
{
var initial =
@"using Bb;
using B;
using bB;
using b;
using Aa;
using a;
using A;
using aa;
using aA;
using AA;
using bb;
using BB;
using bBb;
using bbB;
using ใ;
using ใข;
using ๏ฝฑ;
using ใใ;
using ใใข;
using ใ๏ฝฑ;
using ใขใ;
using cC;
using Cc;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;
using BBb;
using BbB;
using bBB;
using BBB;
using c;
using C;
using bbb;
using Bbb;
using cc;
using cC;
using CC;
// If Kana is sensitive ใ != ใข, if Kana is insensitive ใ == ใข.
// If Width is sensitiveใข != ๏ฝฑ, if Width is insensitive ใข == ๏ฝฑ.";
var final =
@"using a;
using A;
using aa;
using aA;
using Aa;
using AA;
using b;
using B;
using bb;
using bB;
using Bb;
using BB;
using bbb;
using bbB;
using bBb;
using bBB;
using Bbb;
using BbB;
using BBb;
using BBB;
using c;
using C;
using cc;
using cC;
using cC;
using Cc;
using CC;
using ใข;
using ๏ฝฑ;
using ใ;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;
using ใขใ;
using ๏ฝฑใ;
using ใใข;
using ใ๏ฝฑ;
using ใใ;
// If Kana is sensitive ใ != ใข, if Kana is insensitive ใ == ใข.
// If Width is sensitiveใข != ๏ฝฑ, if Width is insensitive ใข == ๏ฝฑ.";
await CheckAsync(initial, final);
}
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task CaseSensitivity2()
{
var initial =
@"using ใ;
using ใข;
using ๏ฝฑ;
using ใใ;
using ใใข;
using ใ๏ฝฑ;
using ใขใ;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;";
var final =
@"using ใข;
using ๏ฝฑ;
using ใ;
using ใขใข;
using ใข๏ฝฑ;
using ๏ฝฑใข;
using ๏ฝฑ๏ฝฑ;
using ใขใ;
using ๏ฝฑใ;
using ใใข;
using ใ๏ฝฑ;
using ใใ;
";
await CheckAsync(initial, final);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping()
{
var initial =
@"// Banner
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using IntList = System.Collections.Generic.List<int>;
using static System.Console;";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true);
}
[WorkItem(20988, "https://github.com/dotnet/roslyn/issues/20988")]
[Fact, Trait(Traits.Feature, Traits.Features.Organizing)]
public async Task TestGrouping2()
{
// Make sure we don't insert extra newlines if they're already there.
var initial =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
var final =
@"// Banner
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
using static System.Console;
using IntList = System.Collections.Generic.List<int>;
";
await CheckAsync(initial, final, placeSystemNamespaceFirst: true, separateImportGroups: true);
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Recommendations/AbstractRecommendationServiceRunner.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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.Recommendations
{
internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext>
where TSyntaxContext : SyntaxContext
{
protected readonly TSyntaxContext _context;
protected readonly bool _filterOutOfScopeLocals;
protected readonly CancellationToken _cancellationToken;
private readonly StringComparer _stringComparerForLanguage;
public AbstractRecommendationServiceRunner(
TSyntaxContext context,
bool filterOutOfScopeLocals,
CancellationToken cancellationToken)
{
_context = context;
_stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer;
_filterOutOfScopeLocals = filterOutOfScopeLocals;
_cancellationToken = cancellationToken;
}
public abstract RecommendedSymbols GetRecommendedSymbols();
public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType);
// This code is to help give intellisense in the following case:
// query.Include(a => a.SomeProperty).ThenInclude(a => a.
// where there are more than one overloads of ThenInclude accepting different types of parameters.
private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable)
{
var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position);
return symbols.IsDefault
? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable)
: symbols;
}
private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position)
{
// Use normal lookup path for this/base parameters.
if (parameter.IsThis)
return default;
// Starting from a. in the example, looking for a => a.
if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod)
return default;
// Cannot proceed without DeclaringSyntaxReferences.
// We expect that there is a single DeclaringSyntaxReferences in the scenario.
// If anything changes on the compiler side, the approach should be revised.
if (owningMethod.DeclaringSyntaxReferences.Length != 1)
return default;
var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>();
// Check that a => a. belongs to an invocation.
// Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a.
var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken);
if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) &&
syntaxFactsService.IsArgument(lambdaSyntax.Parent) &&
syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent)))
{
return default;
}
var invocationExpression = lambdaSyntax.Parent.Parent.Parent;
var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression);
var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent);
var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent);
var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression);
var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty;
if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType))
{
parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType);
}
else
{
// Get all members potentially matching the invocation expression.
// We filter them out based on ordinality later.
var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken);
// parameter.Ordinal is the ordinal within (a,b,c) => b.
// For candidate symbols of (a,b,c) => b., get types of all possible b.
parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal);
// The parameterTypeSymbols may include type parameters, and we want their substituted types if available.
parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression);
}
// For each type of b., return all suitable members. Also, ensure we consider the actual type of the
// parameter the compiler inferred as it may have made a completely suitable inference for it.
return parameterTypeSymbols
.Concat(parameter.Type)
.SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false))
.ToImmutableArray();
}
private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression)
{
if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter)))
{
return parameterTypeSymbols;
}
var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols();
if (invocationSymbols.Length == 0)
{
return parameterTypeSymbols;
}
using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes);
foreach (var invocationSymbol in invocationSymbols)
{
var typeParameters = invocationSymbol.GetTypeParameters();
var typeArguments = invocationSymbol.GetTypeArguments();
foreach (var parameterTypeSymbol in parameterTypeSymbols)
{
if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter))
{
// The typeParameter could be from the containing type, so it may not be
// present in this method's list of typeParameters.
var index = typeParameters.IndexOf(typeParameter);
var concreteType = typeArguments.ElementAtOrDefault(index);
// If we couldn't find the concrete type, still consider the typeParameter
// as is to provide members of any types it is constrained to (including object)
concreteTypes.Add(concreteType ?? typeParameter);
}
else
{
concreteTypes.Add(parameterTypeSymbol);
}
}
}
return concreteTypes.ToImmutable();
}
/// <summary>
/// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol.
/// </summary>
/// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/>
/// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length)
/// </param>
/// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param>
/// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param>
/// <returns></returns>
private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda)
{
var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName);
var builder = ArrayBuilder<ITypeSymbol>.GetInstance();
foreach (var candidateSymbol in candidateSymbols)
{
if (candidateSymbol is IMethodSymbol method)
{
if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type))
{
continue;
}
// If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate.
// Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>.
if (expressionSymbol != null &&
type is INamedTypeSymbol expressionSymbolNamedTypeCandidate &&
expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol))
{
var allTypeArguments = type.GetAllTypeArguments();
if (allTypeArguments.Length != 1)
{
continue;
}
type = allTypeArguments[0];
}
if (type.IsDelegateType())
{
var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName);
if (methods.Length != 1)
{
continue;
}
var parameters = methods[0].GetParameters();
if (parameters.Length <= ordinalInLambda)
{
continue;
}
builder.Add(parameters[ordinalInLambda].Type);
}
}
}
return builder.ToImmutableAndFree().Distinct();
}
private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType)
{
if (!string.IsNullOrEmpty(argumentName))
{
parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type;
return parameterType != null;
}
// We don't know the argument name, so have to find the parameter based on position
if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1))
{
if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType)
{
parameterType = arrayType.ElementType;
return true;
}
else
{
parameterType = null;
return false;
}
}
if (ordinalInInvocation < method.Parameters.Length)
{
parameterType = method.Parameters[ordinalInInvocation].Type;
return true;
}
parameterType = null;
return false;
}
protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>()
where TNamespaceDeclarationSyntax : SyntaxNode
{
var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>();
if (declarationSyntax == null)
return ImmutableArray<ISymbol>.Empty;
var semanticModel = _context.SemanticModel;
var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace(
semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken));
var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol)
.WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax));
return symbols;
}
protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax)
{
//
// Apart from filtering out non-namespace symbols, this also filters out the symbol
// currently being declared. For example...
//
// namespace X$$
//
// ...X won't show in the completion list (unless it is also declared elsewhere).
//
// In addition, in VB, it will filter out Bar from the sample below...
//
// Namespace Goo.$$
// Namespace Bar
// End Namespace
// End Namespace
//
// ...unless, again, it's also declared elsewhere.
//
return recommendationSymbol.IsNamespace() &&
recommendationSymbol.Locations.Any(
candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree &&
declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan)));
}
protected ImmutableArray<ISymbol> GetMemberSymbols(
ISymbol container,
int position,
bool excludeInstance,
bool useBaseReferenceAccessibility,
bool unwrapNullable)
{
// For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter
// information that the compiler may fail to give.
if (container is IParameterSymbol parameter)
return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable);
if (container is not INamespaceOrTypeSymbol namespaceOrType)
return ImmutableArray<ISymbol>.Empty;
if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol)
{
namespaceOrType = typeSymbol.RemoveNullableIfPresent();
}
return useBaseReferenceAccessibility
? _context.SemanticModel.LookupBaseMembers(position)
: LookupSymbolsInContainer(namespaceOrType, position, excludeInstance);
}
protected ImmutableArray<ISymbol> LookupSymbolsInContainer(
INamespaceOrTypeSymbol container, int position, bool excludeInstance)
{
return excludeInstance
? _context.SemanticModel.LookupStaticMembers(position, container)
: SuppressDefaultTupleElements(
container,
_context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true));
}
/// <summary>
/// If container is a tuple type, any of its tuple element which has a friendly name will cause
/// the suppression of the corresponding default name (ItemN).
/// In that case, Rest is also removed.
/// </summary>
protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements(
INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols)
{
var namedType = container as INamedTypeSymbol;
if (namedType?.IsTupleType != true)
{
// container is not a tuple
return symbols;
}
//return tuple elements followed by other members that are not fields
return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements).
Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field));
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.Recommendations
{
internal abstract class AbstractRecommendationServiceRunner<TSyntaxContext>
where TSyntaxContext : SyntaxContext
{
protected readonly TSyntaxContext _context;
protected readonly bool _filterOutOfScopeLocals;
protected readonly CancellationToken _cancellationToken;
private readonly StringComparer _stringComparerForLanguage;
public AbstractRecommendationServiceRunner(
TSyntaxContext context,
bool filterOutOfScopeLocals,
CancellationToken cancellationToken)
{
_context = context;
_stringComparerForLanguage = _context.GetLanguageService<ISyntaxFactsService>().StringComparer;
_filterOutOfScopeLocals = filterOutOfScopeLocals;
_cancellationToken = cancellationToken;
}
public abstract RecommendedSymbols GetRecommendedSymbols();
public abstract bool TryGetExplicitTypeOfLambdaParameter(SyntaxNode lambdaSyntax, int ordinalInLambda, [NotNullWhen(returnValue: true)] out ITypeSymbol explicitLambdaParameterType);
// This code is to help give intellisense in the following case:
// query.Include(a => a.SomeProperty).ThenInclude(a => a.
// where there are more than one overloads of ThenInclude accepting different types of parameters.
private ImmutableArray<ISymbol> GetMemberSymbolsForParameter(IParameterSymbol parameter, int position, bool useBaseReferenceAccessibility, bool unwrapNullable)
{
var symbols = TryGetMemberSymbolsForLambdaParameter(parameter, position);
return symbols.IsDefault
? GetMemberSymbols(parameter.Type, position, excludeInstance: false, useBaseReferenceAccessibility, unwrapNullable)
: symbols;
}
private ImmutableArray<ISymbol> TryGetMemberSymbolsForLambdaParameter(IParameterSymbol parameter, int position)
{
// Use normal lookup path for this/base parameters.
if (parameter.IsThis)
return default;
// Starting from a. in the example, looking for a => a.
if (parameter.ContainingSymbol is not IMethodSymbol { MethodKind: MethodKind.AnonymousFunction } owningMethod)
return default;
// Cannot proceed without DeclaringSyntaxReferences.
// We expect that there is a single DeclaringSyntaxReferences in the scenario.
// If anything changes on the compiler side, the approach should be revised.
if (owningMethod.DeclaringSyntaxReferences.Length != 1)
return default;
var syntaxFactsService = _context.GetLanguageService<ISyntaxFactsService>();
// Check that a => a. belongs to an invocation.
// Find its' ordinal in the invocation, e.g. ThenInclude(a => a.Something, a=> a.
var lambdaSyntax = owningMethod.DeclaringSyntaxReferences.Single().GetSyntax(_cancellationToken);
if (!(syntaxFactsService.IsAnonymousFunction(lambdaSyntax) &&
syntaxFactsService.IsArgument(lambdaSyntax.Parent) &&
syntaxFactsService.IsInvocationExpression(lambdaSyntax.Parent.Parent.Parent)))
{
return default;
}
var invocationExpression = lambdaSyntax.Parent.Parent.Parent;
var arguments = syntaxFactsService.GetArgumentsOfInvocationExpression(invocationExpression);
var argumentName = syntaxFactsService.GetNameForArgument(lambdaSyntax.Parent);
var ordinalInInvocation = arguments.IndexOf(lambdaSyntax.Parent);
var expressionOfInvocationExpression = syntaxFactsService.GetExpressionOfInvocationExpression(invocationExpression);
var parameterTypeSymbols = ImmutableArray<ITypeSymbol>.Empty;
if (TryGetExplicitTypeOfLambdaParameter(lambdaSyntax, parameter.Ordinal, out var explicitLambdaParameterType))
{
parameterTypeSymbols = ImmutableArray.Create(explicitLambdaParameterType);
}
else
{
// Get all members potentially matching the invocation expression.
// We filter them out based on ordinality later.
var candidateSymbols = _context.SemanticModel.GetMemberGroup(expressionOfInvocationExpression, _cancellationToken);
// parameter.Ordinal is the ordinal within (a,b,c) => b.
// For candidate symbols of (a,b,c) => b., get types of all possible b.
parameterTypeSymbols = GetTypeSymbols(candidateSymbols, argumentName, ordinalInInvocation, ordinalInLambda: parameter.Ordinal);
// The parameterTypeSymbols may include type parameters, and we want their substituted types if available.
parameterTypeSymbols = SubstituteTypeParameters(parameterTypeSymbols, invocationExpression);
}
// For each type of b., return all suitable members. Also, ensure we consider the actual type of the
// parameter the compiler inferred as it may have made a completely suitable inference for it.
return parameterTypeSymbols
.Concat(parameter.Type)
.SelectMany(parameterTypeSymbol => GetMemberSymbols(parameterTypeSymbol, position, excludeInstance: false, useBaseReferenceAccessibility: false, unwrapNullable: false))
.ToImmutableArray();
}
private ImmutableArray<ITypeSymbol> SubstituteTypeParameters(ImmutableArray<ITypeSymbol> parameterTypeSymbols, SyntaxNode invocationExpression)
{
if (!parameterTypeSymbols.Any(t => t.IsKind(SymbolKind.TypeParameter)))
{
return parameterTypeSymbols;
}
var invocationSymbols = _context.SemanticModel.GetSymbolInfo(invocationExpression).GetAllSymbols();
if (invocationSymbols.Length == 0)
{
return parameterTypeSymbols;
}
using var _ = ArrayBuilder<ITypeSymbol>.GetInstance(out var concreteTypes);
foreach (var invocationSymbol in invocationSymbols)
{
var typeParameters = invocationSymbol.GetTypeParameters();
var typeArguments = invocationSymbol.GetTypeArguments();
foreach (var parameterTypeSymbol in parameterTypeSymbols)
{
if (parameterTypeSymbol.IsKind<ITypeParameterSymbol>(SymbolKind.TypeParameter, out var typeParameter))
{
// The typeParameter could be from the containing type, so it may not be
// present in this method's list of typeParameters.
var index = typeParameters.IndexOf(typeParameter);
var concreteType = typeArguments.ElementAtOrDefault(index);
// If we couldn't find the concrete type, still consider the typeParameter
// as is to provide members of any types it is constrained to (including object)
concreteTypes.Add(concreteType ?? typeParameter);
}
else
{
concreteTypes.Add(parameterTypeSymbol);
}
}
}
return concreteTypes.ToImmutable();
}
/// <summary>
/// Tries to get a type of its' <paramref name="ordinalInLambda"/> lambda parameter of <paramref name="ordinalInInvocation"/> argument for each candidate symbol.
/// </summary>
/// <param name="candidateSymbols">symbols corresponding to <see cref="Expression{Func}"/> or <see cref="Func{some_args, TResult}"/>
/// Here, some_args can be multi-variables lambdas as well, e.g. f((a,b) => a+b, (a,b,c)=>a*b*c.Length)
/// </param>
/// <param name="ordinalInInvocation">ordinal of the arguments of function: (a,b) or (a,b,c) in the example above</param>
/// <param name="ordinalInLambda">ordinal of the lambda parameters, e.g. a, b or c.</param>
/// <returns></returns>
private ImmutableArray<ITypeSymbol> GetTypeSymbols(ImmutableArray<ISymbol> candidateSymbols, string argumentName, int ordinalInInvocation, int ordinalInLambda)
{
var expressionSymbol = _context.SemanticModel.Compilation.GetTypeByMetadataName(typeof(Expression<>).FullName);
var builder = ArrayBuilder<ITypeSymbol>.GetInstance();
foreach (var candidateSymbol in candidateSymbols)
{
if (candidateSymbol is IMethodSymbol method)
{
if (!TryGetMatchingParameterTypeForArgument(method, argumentName, ordinalInInvocation, out var type))
{
continue;
}
// If type is <see cref="Expression{TDelegate}"/>, ignore <see cref="Expression"/> and use TDelegate.
// Ignore this check if expressionSymbol is null, e.g. semantic model is broken or incomplete or if the framework does not contain <see cref="Expression"/>.
if (expressionSymbol != null &&
type is INamedTypeSymbol expressionSymbolNamedTypeCandidate &&
expressionSymbolNamedTypeCandidate.OriginalDefinition.Equals(expressionSymbol))
{
var allTypeArguments = type.GetAllTypeArguments();
if (allTypeArguments.Length != 1)
{
continue;
}
type = allTypeArguments[0];
}
if (type.IsDelegateType())
{
var methods = type.GetMembers(WellKnownMemberNames.DelegateInvokeName);
if (methods.Length != 1)
{
continue;
}
var parameters = methods[0].GetParameters();
if (parameters.Length <= ordinalInLambda)
{
continue;
}
builder.Add(parameters[ordinalInLambda].Type);
}
}
}
return builder.ToImmutableAndFree().Distinct();
}
private bool TryGetMatchingParameterTypeForArgument(IMethodSymbol method, string argumentName, int ordinalInInvocation, out ITypeSymbol parameterType)
{
if (!string.IsNullOrEmpty(argumentName))
{
parameterType = method.Parameters.FirstOrDefault(p => _stringComparerForLanguage.Equals(p.Name, argumentName))?.Type;
return parameterType != null;
}
// We don't know the argument name, so have to find the parameter based on position
if (method.IsParams() && (ordinalInInvocation >= method.Parameters.Length - 1))
{
if (method.Parameters.LastOrDefault()?.Type is IArrayTypeSymbol arrayType)
{
parameterType = arrayType.ElementType;
return true;
}
else
{
parameterType = null;
return false;
}
}
if (ordinalInInvocation < method.Parameters.Length)
{
parameterType = method.Parameters[ordinalInInvocation].Type;
return true;
}
parameterType = null;
return false;
}
protected ImmutableArray<ISymbol> GetSymbolsForNamespaceDeclarationNameContext<TNamespaceDeclarationSyntax>()
where TNamespaceDeclarationSyntax : SyntaxNode
{
var declarationSyntax = _context.TargetToken.GetAncestor<TNamespaceDeclarationSyntax>();
if (declarationSyntax == null)
return ImmutableArray<ISymbol>.Empty;
var semanticModel = _context.SemanticModel;
var containingNamespaceSymbol = semanticModel.Compilation.GetCompilationNamespace(
semanticModel.GetEnclosingNamespace(declarationSyntax.SpanStart, _cancellationToken));
var symbols = semanticModel.LookupNamespacesAndTypes(declarationSyntax.SpanStart, containingNamespaceSymbol)
.WhereAsArray(recommendationSymbol => IsNonIntersectingNamespace(recommendationSymbol, declarationSyntax));
return symbols;
}
protected static bool IsNonIntersectingNamespace(ISymbol recommendationSymbol, SyntaxNode declarationSyntax)
{
//
// Apart from filtering out non-namespace symbols, this also filters out the symbol
// currently being declared. For example...
//
// namespace X$$
//
// ...X won't show in the completion list (unless it is also declared elsewhere).
//
// In addition, in VB, it will filter out Bar from the sample below...
//
// Namespace Goo.$$
// Namespace Bar
// End Namespace
// End Namespace
//
// ...unless, again, it's also declared elsewhere.
//
return recommendationSymbol.IsNamespace() &&
recommendationSymbol.Locations.Any(
candidateLocation => !(declarationSyntax.SyntaxTree == candidateLocation.SourceTree &&
declarationSyntax.Span.IntersectsWith(candidateLocation.SourceSpan)));
}
protected ImmutableArray<ISymbol> GetMemberSymbols(
ISymbol container,
int position,
bool excludeInstance,
bool useBaseReferenceAccessibility,
bool unwrapNullable)
{
// For a normal parameter, we have a specialized codepath we use to ensure we properly get lambda parameter
// information that the compiler may fail to give.
if (container is IParameterSymbol parameter)
return GetMemberSymbolsForParameter(parameter, position, useBaseReferenceAccessibility, unwrapNullable);
if (container is not INamespaceOrTypeSymbol namespaceOrType)
return ImmutableArray<ISymbol>.Empty;
if (unwrapNullable && namespaceOrType is ITypeSymbol typeSymbol)
{
namespaceOrType = typeSymbol.RemoveNullableIfPresent();
}
return useBaseReferenceAccessibility
? _context.SemanticModel.LookupBaseMembers(position)
: LookupSymbolsInContainer(namespaceOrType, position, excludeInstance);
}
protected ImmutableArray<ISymbol> LookupSymbolsInContainer(
INamespaceOrTypeSymbol container, int position, bool excludeInstance)
{
return excludeInstance
? _context.SemanticModel.LookupStaticMembers(position, container)
: SuppressDefaultTupleElements(
container,
_context.SemanticModel.LookupSymbols(position, container, includeReducedExtensionMethods: true));
}
/// <summary>
/// If container is a tuple type, any of its tuple element which has a friendly name will cause
/// the suppression of the corresponding default name (ItemN).
/// In that case, Rest is also removed.
/// </summary>
protected static ImmutableArray<ISymbol> SuppressDefaultTupleElements(
INamespaceOrTypeSymbol container, ImmutableArray<ISymbol> symbols)
{
var namedType = container as INamedTypeSymbol;
if (namedType?.IsTupleType != true)
{
// container is not a tuple
return symbols;
}
//return tuple elements followed by other members that are not fields
return ImmutableArray<ISymbol>.CastUp(namedType.TupleElements).
Concat(symbols.WhereAsArray(s => s.Kind != SymbolKind.Field));
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Extensions/SyntaxNodeExtensions.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.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxNodeExtensions
{
public static void Deconstruct(this SyntaxNode node, out SyntaxKind kind)
{
kind = node.Kind();
}
public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsKind(kind))
{
result = (TNode)node;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind)
=> CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind);
public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsParentKind(kind))
{
result = (TNode)node.Parent!;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
=> IsKind(node?.Parent, kind1, kind2);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
=> IsKind(node?.Parent, kind1, kind2, kind3);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
=> IsKind(node?.Parent, kind1, kind2, kind3, kind4);
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11;
}
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxNode node, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
=> node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken(
sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine);
/// <summary>
/// Returns all of the trivia to the left of this token up to the previous token (concatenates
/// the previous token's trailing trivia and this token's leading trivia).
/// </summary>
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxToken token, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
{
var prevToken = token.GetPreviousToken(includeSkipped: true);
if (prevToken.Kind() == SyntaxKind.None)
{
return token.LeadingTrivia;
}
Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too.");
if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine &&
!sourceText!.AreOnSameLine(prevToken, token))
{
return token.LeadingTrivia;
}
return prevToken.TrailingTrivia.Concat(token.LeadingTrivia);
}
public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.ArgumentList) ||
node.IsKind(SyntaxKind.AttributeArgumentList) ||
node.IsKind(SyntaxKind.BracketedArgumentList) ||
node.IsKind(SyntaxKind.TypeArgumentList);
}
public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node)
{
switch (node)
{
case NamespaceDeclarationSyntax namespaceNode:
return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken);
case BaseTypeDeclarationSyntax baseTypeNode:
return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken);
case AccessorListSyntax accessorListNode:
return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken);
case BlockSyntax blockNode:
return (blockNode.OpenBraceToken, blockNode.CloseBraceToken);
case SwitchStatementSyntax switchStatementNode:
return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken);
case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression:
return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken);
case InitializerExpressionSyntax initializeExpressionNode:
return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken);
case SwitchExpressionSyntax switchExpression:
return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken);
case PropertyPatternClauseSyntax property:
return (property.OpenBraceToken, property.CloseBraceToken);
case WithExpressionSyntax withExpr:
return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken);
case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }:
return (initializer.OpenBraceToken, initializer.CloseBraceToken);
}
return default;
}
public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node is DoStatementSyntax ||
node is ElseClauseSyntax ||
node is FixedStatementSyntax ||
node is CommonForEachStatementSyntax ||
node is ForStatementSyntax ||
node is IfStatementSyntax ||
node is LabeledStatementSyntax ||
node is LockStatementSyntax ||
node is UsingStatementSyntax ||
node is WhileStatementSyntax;
}
public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node)
=> node switch
{
DoStatementSyntax n => n.Statement,
ElseClauseSyntax n => n.Statement,
FixedStatementSyntax n => n.Statement,
CommonForEachStatementSyntax n => n.Statement,
ForStatementSyntax n => n.Statement,
IfStatementSyntax n => n.Statement,
LabeledStatementSyntax n => n.Statement,
LockStatementSyntax n => n.Statement,
UsingStatementSyntax n => n.Statement,
WhileStatementSyntax n => n.Statement,
_ => null,
};
public static BaseParameterListSyntax? GetParameterList(this SyntaxNode? declaration)
=> declaration?.Kind() switch
{
SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList,
SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList,
SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList,
SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList,
SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList,
SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration => ((RecordDeclarationSyntax)declaration).ParameterList,
_ => null,
};
public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration)
=> declaration switch
{
MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists,
AccessorDeclarationSyntax accessor => accessor.AttributeLists,
ParameterSyntax parameter => parameter.AttributeLists,
CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists,
_ => default,
};
public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node)
{
// Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in
// LanguageParser.ParseConsequenceSyntax).
// These are the parts of the expression that the ?... expression can end with. Specifically:
//
// 1. x?.y.M() // invocation
// 2. x?.y[...]; // element access
// 3. x?.y.z // member access
// 4. x?.y // member binding
// 5. x?[y] // element binding
var current = node;
if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) ||
(current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current))
{
current = current.Parent;
}
// Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first
// conditional access.
while (current.IsKind(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.MemberBindingExpression,
SyntaxKind.ElementBindingExpression) &&
current.Parent is not ConditionalAccessExpressionSyntax)
{
current = current.Parent;
}
// Two cases we have to care about:
//
// 1. a?.b.$$c.d and
// 2. a?.b.$$c.d?.e...
//
// Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are
// lower in the tree and are not seen as we walk upwards.
//
//
// To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the
// right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a
// another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction:
//
// a?.b.$$c.d?.e // it will do:
// ----->
// <---------
//
// Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to
// get the root parent in a case like:
//
// x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do:
// ----->
// <---------
// <---
// <---
// <---
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.Expression == current)
{
current = conditional;
}
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current as ConditionalAccessExpressionSyntax;
}
/// <summary>
/// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/>
/// </summary>>
public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node)
{
// Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at
// the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with
// `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE
// sequence).
var current = node.GetParentConditionalAccessExpression();
while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current;
}
public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node)
{
if (!(node is ConditionalAccessExpressionSyntax))
{
return null;
}
var result = (ConditionalAccessExpressionSyntax)node;
while (result.WhenNotNull is ConditionalAccessExpressionSyntax)
{
result = (ConditionalAccessExpressionSyntax)result.WhenNotNull;
}
return result;
}
public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.MethodDeclaration)
|| node.IsAnyLambdaOrAnonymousMethod()
|| node.IsKind(SyntaxKind.LocalFunctionStatement);
}
public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return
node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) ||
node.IsKind(SyntaxKind.SimpleLambdaExpression);
}
public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression);
public static bool IsAnyAssignExpression(this SyntaxNode node)
=> SyntaxFacts.IsAssignmentExpression(node.Kind());
public static bool IsCompoundAssignExpression(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
return true;
}
return false;
}
public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) &&
assignment.Left == node;
public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Right == node;
}
public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsCompoundAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
/// <summary>
/// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in
/// top down order.
/// </summary>
public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings
.Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Usings));
}
public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs
.Concat(node.GetAncestorsOrThis<NamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Externs));
}
public static bool IsUnsafeContext(this SyntaxNode node)
{
if (node.GetAncestor<UnsafeStatementSyntax>() != null)
{
return true;
}
return node.GetAncestors<MemberDeclarationSyntax>().Any(
m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsInStaticContext(this SyntaxNode node)
{
// this/base calls are always static.
if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
{
return true;
}
var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (memberDeclaration == null)
{
return false;
}
switch (memberDeclaration.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) ||
node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Inside a field one can only access static members of a type (unless it's top-level).
return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit);
case SyntaxKind.DestructorDeclaration:
return false;
}
// Global statements are not a static context.
if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
{
return false;
}
// any other location is considered static
return true;
}
public static NamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor == null)
{
return contextNode.GetAncestorsOrThis<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
else
{
// We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings.
var containingNamespace = usingDirectiveAncestor.GetAncestor<NamespaceDeclarationSyntax>();
if (containingNamespace == null)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return null;
}
else
{
return containingNamespace.GetAncestors<NamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
}
}
public static bool IsBreakableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsContinuableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsReturnableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.LocalFunctionStatement:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
}
return false;
}
public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list);
[return: NotNullIfNotNull("node")]
public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false)
where TNode : SyntaxNode
{
if (node == null)
{
return node;
}
var rewriter = new SingleLineRewriter(useElasticTrivia);
return (TNode)rewriter.Visit(node);
}
/// <summary>
/// Returns true if the passed in node contains an interleaved pp directive.
///
/// i.e. The following returns false:
///
/// void Goo() {
/// #if true
/// #endif
/// }
///
/// #if true
/// void Goo() {
/// }
/// #endif
///
/// but these return true:
///
/// #if true
/// void Goo() {
/// #endif
/// }
///
/// void Goo() {
/// #if true
/// }
/// #endif
///
/// #if true
/// void Goo() {
/// #else
/// }
/// #endif
///
/// i.e. the method returns true if it contains a PP directive that belongs to a grouping
/// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't
/// entirely contained within the span of the node.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken);
/// <summary>
/// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check
/// for interleaved directives can be specified separately to the node passed in.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken);
public static bool ContainsInterleavedDirective(
this SyntaxToken token,
TextSpan textSpan,
CancellationToken cancellationToken)
{
return
ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) ||
ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken);
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTriviaList list,
CancellationToken cancellationToken)
{
foreach (var trivia in list)
{
if (textSpan.Contains(trivia.Span))
{
if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken))
{
return true;
}
}
}
return false;
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTrivia trivia,
CancellationToken cancellationToken)
{
if (trivia.HasStructure)
{
var structure = trivia.GetStructure()!;
if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia,
SyntaxKind.EndRegionDirectiveTrivia,
SyntaxKind.IfDirectiveTrivia,
SyntaxKind.EndIfDirectiveTrivia))
{
var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken);
if (match != null)
{
var matchSpan = match.Span;
if (!textSpan.Contains(matchSpan.Start))
{
// The match for this pp directive is outside
// this node.
return true;
}
}
}
else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia))
{
var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken);
if (directives != null && directives.Count > 0)
{
if (!textSpan.Contains(directives[0].SpanStart) ||
!textSpan.Contains(directives[directives.Count - 1].SpanStart))
{
// This else/elif belongs to a pp span that isn't
// entirely within this node.
return true;
}
}
}
}
return false;
}
/// <summary>
/// Breaks up the list of provided nodes, based on how they are interspersed with pp
/// directives, into groups. Within these groups nodes can be moved around safely, without
/// breaking any pp constructs.
/// </summary>
public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>(
this IEnumerable<TSyntaxNode> nodes,
CancellationToken cancellationToken)
where TSyntaxNode : SyntaxNode
{
var result = new List<IList<TSyntaxNode>>();
var currentGroup = new List<TSyntaxNode>();
foreach (var node in nodes)
{
var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken);
var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind()));
if (hasUnmatchedInteriorDirective)
{
// we have a #if/#endif/#region/#endregion/#else/#elif in
// this node that belongs to a span of pp directives that
// is not entirely contained within the node. i.e.:
//
// void Goo() {
// #if ...
// }
//
// This node cannot be moved at all. It is in a group that
// only contains itself (and thus can never be moved).
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
result.Add(new List<TSyntaxNode> { node });
}
else if (hasLeadingDirective)
{
// We have a PP directive before us. i.e.:
//
// #if ...
// void Goo() {
//
// That means we start a new group that is contained between
// the above directive and the following directive.
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
currentGroup.Add(node);
}
else
{
// simple case. just add ourselves to the current group
currentGroup.Add(node);
}
}
// add the remainder of the final group.
result.Add(currentGroup);
// Now, filter out any empty groups.
result = result.Where(group => !group.IsEmpty()).ToList();
return result;
}
public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia);
public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia);
public static bool IsVariableDeclaratorValue(this SyntaxNode node)
=> node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) &&
equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) &&
equalsValue.Value == node;
public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode<BlockSyntax>();
public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate)
{
var current = node;
while (current != null)
{
if (predicate(current))
{
yield return current;
}
current = current.Parent;
}
}
/// <summary>
/// Returns child node or token that contains given position.
/// </summary>
/// <remarks>
/// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
/// </remarks>
internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex)
{
var childList = self.ChildNodesAndTokens();
var left = 0;
var right = childList.Count - 1;
while (left <= right)
{
var middle = left + ((right - left) / 2);
var node = childList[middle];
var span = node.FullSpan;
if (position < span.Start)
{
right = middle - 1;
}
else if (position >= span.End)
{
left = middle + 1;
}
else
{
childIndex = middle;
return node;
}
}
// we could check up front that index is within FullSpan,
// but we wan to optimize for the common case where position is valid.
Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?");
throw new ArgumentOutOfRangeException(nameof(position));
}
public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node)
{
switch (node)
{
case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken);
case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
default: return default;
}
}
public static (SyntaxToken openBracket, SyntaxToken closeBracket) GetBrackets(this SyntaxNode node)
{
switch (node)
{
case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
default: return default;
}
}
public static SyntaxTokenList GetModifiers(this SyntaxNode? member)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers;
case AccessorDeclarationSyntax accessor: return accessor.Modifiers;
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.Modifiers;
case LocalFunctionStatementSyntax localFunction: return localFunction.Modifiers;
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.Modifiers;
}
return default;
}
public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers);
case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers);
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.WithModifiers(modifiers);
case LocalFunctionStatementSyntax localFunction: return localFunction.WithModifiers(modifiers);
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.WithModifiers(modifiers);
}
return null;
}
public static bool CheckTopLevel(this SyntaxNode node, TextSpan span)
{
switch (node)
{
case BlockSyntax block:
return block.ContainsInBlockBody(span);
case ArrowExpressionClauseSyntax expressionBodiedMember:
return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span);
case FieldDeclarationSyntax field:
{
foreach (var variable in field.Declaration.Variables)
{
if (variable.Initializer != null && variable.Initializer.Span.Contains(span))
{
return true;
}
}
break;
}
case GlobalStatementSyntax _:
return true;
case ConstructorInitializerSyntax constructorInitializer:
return constructorInitializer.ContainsInArgument(span);
}
return false;
}
public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan)
{
if (initializer == null)
{
return false;
}
return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan));
}
public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan)
{
if (block == null)
{
return false;
}
var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart);
return blockSpan.Contains(textSpan);
}
public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan)
{
if (expressionBodiedMember == null)
{
return false;
}
var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End);
return expressionBodiedMemberBody.Contains(textSpan);
}
public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node)
{
switch (node)
{
case CompilationUnitSyntax compilation:
return compilation.Members;
case BaseNamespaceDeclarationSyntax @namespace:
return @namespace.Members;
case TypeDeclarationSyntax type:
return type.Members;
case EnumDeclarationSyntax @enum:
return @enum.Members;
}
return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>();
}
public static bool IsInExpressionTree(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
SemanticModel semanticModel,
[NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt,
CancellationToken cancellationToken)
{
if (expressionTypeOpt != null)
{
for (var current = node; current != null; current = current.Parent)
{
if (current.IsAnyLambda())
{
var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken);
if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition))
return true;
}
else if (current is SelectOrGroupClauseSyntax ||
current is OrderingSyntax)
{
var info = semanticModel.GetSymbolInfo(current, cancellationToken);
if (TakesExpressionTree(info, expressionTypeOpt))
return true;
}
else if (current is QueryClauseSyntax queryClause)
{
var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken);
if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) ||
TakesExpressionTree(info.OperationInfo, expressionTypeOpt))
{
return true;
}
}
}
}
return false;
static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType)
{
foreach (var symbol in info.GetAllSymbols())
{
if (symbol is IMethodSymbol method &&
method.Parameters.Length > 0 &&
expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition))
{
return true;
}
}
return false;
}
}
public static bool IsInDeconstructionLeft(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
[NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft)
{
SyntaxNode? previous = null;
for (var current = node; current != null; current = current.Parent)
{
if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) ||
(current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable))
{
deconstructionLeft = previous;
return true;
}
if (current is StatementSyntax)
{
break;
}
previous = current;
}
deconstructionLeft = null;
return false;
}
public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node)
=> node switch
{
{ Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true,
{ Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true,
_ => false
};
public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken)
where T : SyntaxNode
=> node.WithCommentsFrom(
SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken),
SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken));
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxToken> leadingTokens,
IEnumerable<SyntaxToken> trailingTokens)
where T : SyntaxNode
=> node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia());
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxTrivia> leadingTrivia,
IEnumerable<SyntaxTrivia> trailingTrivia,
params SyntaxNodeOrToken[] trailingNodesOrTokens)
where T : SyntaxNode
=> node
.WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false))
.WithTrailingTrivia(
node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false));
public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode
=> node
.WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true))
.WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: 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.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static partial class SyntaxNodeExtensions
{
public static void Deconstruct(this SyntaxNode node, out SyntaxKind kind)
{
kind = node.Kind();
}
public static bool IsKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsKind(kind))
{
result = (TNode)node;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind)
=> CodeAnalysis.CSharpExtensions.IsKind(node?.Parent, kind);
public static bool IsParentKind<TNode>([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind, [NotNullWhen(returnValue: true)] out TNode? result)
where TNode : SyntaxNode
{
if (node.IsParentKind(kind))
{
result = (TNode)node.Parent!;
return true;
}
result = null;
return false;
}
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
=> IsKind(node?.Parent, kind1, kind2);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
=> IsKind(node?.Parent, kind1, kind2, kind3);
public static bool IsParentKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
=> IsKind(node?.Parent, kind1, kind2, kind3, kind4);
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10;
}
public static bool IsKind([NotNullWhen(returnValue: true)] this SyntaxNode? node, SyntaxKind kind1, SyntaxKind kind2, SyntaxKind kind3, SyntaxKind kind4, SyntaxKind kind5, SyntaxKind kind6, SyntaxKind kind7, SyntaxKind kind8, SyntaxKind kind9, SyntaxKind kind10, SyntaxKind kind11)
{
if (node == null)
{
return false;
}
var csharpKind = node.Kind();
return csharpKind == kind1 || csharpKind == kind2 || csharpKind == kind3 || csharpKind == kind4 || csharpKind == kind5 || csharpKind == kind6 || csharpKind == kind7 || csharpKind == kind8 || csharpKind == kind9 || csharpKind == kind10 || csharpKind == kind11;
}
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxNode node, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
=> node.GetFirstToken().GetAllPrecedingTriviaToPreviousToken(
sourceText, includePreviousTokenTrailingTriviaOnlyIfOnSameLine);
/// <summary>
/// Returns all of the trivia to the left of this token up to the previous token (concatenates
/// the previous token's trailing trivia and this token's leading trivia).
/// </summary>
public static IEnumerable<SyntaxTrivia> GetAllPrecedingTriviaToPreviousToken(
this SyntaxToken token, SourceText? sourceText = null,
bool includePreviousTokenTrailingTriviaOnlyIfOnSameLine = false)
{
var prevToken = token.GetPreviousToken(includeSkipped: true);
if (prevToken.Kind() == SyntaxKind.None)
{
return token.LeadingTrivia;
}
Contract.ThrowIfTrue(sourceText == null && includePreviousTokenTrailingTriviaOnlyIfOnSameLine, "If we are including previous token trailing trivia, we need the text too.");
if (includePreviousTokenTrailingTriviaOnlyIfOnSameLine &&
!sourceText!.AreOnSameLine(prevToken, token))
{
return token.LeadingTrivia;
}
return prevToken.TrailingTrivia.Concat(token.LeadingTrivia);
}
public static bool IsAnyArgumentList([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.ArgumentList) ||
node.IsKind(SyntaxKind.AttributeArgumentList) ||
node.IsKind(SyntaxKind.BracketedArgumentList) ||
node.IsKind(SyntaxKind.TypeArgumentList);
}
public static (SyntaxToken openBrace, SyntaxToken closeBrace) GetBraces(this SyntaxNode? node)
{
switch (node)
{
case NamespaceDeclarationSyntax namespaceNode:
return (namespaceNode.OpenBraceToken, namespaceNode.CloseBraceToken);
case BaseTypeDeclarationSyntax baseTypeNode:
return (baseTypeNode.OpenBraceToken, baseTypeNode.CloseBraceToken);
case AccessorListSyntax accessorListNode:
return (accessorListNode.OpenBraceToken, accessorListNode.CloseBraceToken);
case BlockSyntax blockNode:
return (blockNode.OpenBraceToken, blockNode.CloseBraceToken);
case SwitchStatementSyntax switchStatementNode:
return (switchStatementNode.OpenBraceToken, switchStatementNode.CloseBraceToken);
case AnonymousObjectCreationExpressionSyntax anonymousObjectCreationExpression:
return (anonymousObjectCreationExpression.OpenBraceToken, anonymousObjectCreationExpression.CloseBraceToken);
case InitializerExpressionSyntax initializeExpressionNode:
return (initializeExpressionNode.OpenBraceToken, initializeExpressionNode.CloseBraceToken);
case SwitchExpressionSyntax switchExpression:
return (switchExpression.OpenBraceToken, switchExpression.CloseBraceToken);
case PropertyPatternClauseSyntax property:
return (property.OpenBraceToken, property.CloseBraceToken);
case WithExpressionSyntax withExpr:
return (withExpr.Initializer.OpenBraceToken, withExpr.Initializer.CloseBraceToken);
case ImplicitObjectCreationExpressionSyntax { Initializer: { } initializer }:
return (initializer.OpenBraceToken, initializer.CloseBraceToken);
}
return default;
}
public static bool IsEmbeddedStatementOwner([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node is DoStatementSyntax ||
node is ElseClauseSyntax ||
node is FixedStatementSyntax ||
node is CommonForEachStatementSyntax ||
node is ForStatementSyntax ||
node is IfStatementSyntax ||
node is LabeledStatementSyntax ||
node is LockStatementSyntax ||
node is UsingStatementSyntax ||
node is WhileStatementSyntax;
}
public static StatementSyntax? GetEmbeddedStatement(this SyntaxNode? node)
=> node switch
{
DoStatementSyntax n => n.Statement,
ElseClauseSyntax n => n.Statement,
FixedStatementSyntax n => n.Statement,
CommonForEachStatementSyntax n => n.Statement,
ForStatementSyntax n => n.Statement,
IfStatementSyntax n => n.Statement,
LabeledStatementSyntax n => n.Statement,
LockStatementSyntax n => n.Statement,
UsingStatementSyntax n => n.Statement,
WhileStatementSyntax n => n.Statement,
_ => null,
};
public static BaseParameterListSyntax? GetParameterList(this SyntaxNode? declaration)
=> declaration?.Kind() switch
{
SyntaxKind.DelegateDeclaration => ((DelegateDeclarationSyntax)declaration).ParameterList,
SyntaxKind.MethodDeclaration => ((MethodDeclarationSyntax)declaration).ParameterList,
SyntaxKind.OperatorDeclaration => ((OperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConversionOperatorDeclaration => ((ConversionOperatorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ConstructorDeclaration => ((ConstructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.DestructorDeclaration => ((DestructorDeclarationSyntax)declaration).ParameterList,
SyntaxKind.IndexerDeclaration => ((IndexerDeclarationSyntax)declaration).ParameterList,
SyntaxKind.ParenthesizedLambdaExpression => ((ParenthesizedLambdaExpressionSyntax)declaration).ParameterList,
SyntaxKind.LocalFunctionStatement => ((LocalFunctionStatementSyntax)declaration).ParameterList,
SyntaxKind.AnonymousMethodExpression => ((AnonymousMethodExpressionSyntax)declaration).ParameterList,
SyntaxKind.RecordDeclaration or SyntaxKind.RecordStructDeclaration => ((RecordDeclarationSyntax)declaration).ParameterList,
_ => null,
};
public static SyntaxList<AttributeListSyntax> GetAttributeLists(this SyntaxNode? declaration)
=> declaration switch
{
MemberDeclarationSyntax memberDecl => memberDecl.AttributeLists,
AccessorDeclarationSyntax accessor => accessor.AttributeLists,
ParameterSyntax parameter => parameter.AttributeLists,
CompilationUnitSyntax compilationUnit => compilationUnit.AttributeLists,
_ => default,
};
public static ConditionalAccessExpressionSyntax? GetParentConditionalAccessExpression(this SyntaxNode? node)
{
// Walk upwards based on the grammar/parser rules around ?. expressions (can be seen in
// LanguageParser.ParseConsequenceSyntax).
// These are the parts of the expression that the ?... expression can end with. Specifically:
//
// 1. x?.y.M() // invocation
// 2. x?.y[...]; // element access
// 3. x?.y.z // member access
// 4. x?.y // member binding
// 5. x?[y] // element binding
var current = node;
if ((current.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, out MemberAccessExpressionSyntax? memberAccess) && memberAccess.Name == current) ||
(current.IsParentKind(SyntaxKind.MemberBindingExpression, out MemberBindingExpressionSyntax? memberBinding) && memberBinding.Name == current))
{
current = current.Parent;
}
// Effectively, if we're on the RHS of the ? we have to walk up the RHS spine first until we hit the first
// conditional access.
while (current.IsKind(
SyntaxKind.InvocationExpression,
SyntaxKind.ElementAccessExpression,
SyntaxKind.SimpleMemberAccessExpression,
SyntaxKind.MemberBindingExpression,
SyntaxKind.ElementBindingExpression) &&
current.Parent is not ConditionalAccessExpressionSyntax)
{
current = current.Parent;
}
// Two cases we have to care about:
//
// 1. a?.b.$$c.d and
// 2. a?.b.$$c.d?.e...
//
// Note that `a?.b.$$c.d?.e.f?.g.h.i` falls into the same bucket as two. i.e. the parts after `.e` are
// lower in the tree and are not seen as we walk upwards.
//
//
// To get the root ?. (the one after the `a`) we have to potentially consume the first ?. on the RHS of the
// right spine (i.e. the one after `d`). Once we do this, we then see if that itself is on the RHS of a
// another conditional, and if so we hten return the one on the left. i.e. for '2' this goes in this direction:
//
// a?.b.$$c.d?.e // it will do:
// ----->
// <---------
//
// Note that this only one CAE consumption on both sides. GetRootConditionalAccessExpression can be used to
// get the root parent in a case like:
//
// x?.y?.z?.a?.b.$$c.d?.e.f?.g.h.i // it will do:
// ----->
// <---------
// <---
// <---
// <---
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.Expression == current)
{
current = conditional;
}
if (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current as ConditionalAccessExpressionSyntax;
}
/// <summary>
/// <inheritdoc cref="ISyntaxFacts.GetRootConditionalAccessExpression(SyntaxNode)"/>
/// </summary>>
public static ConditionalAccessExpressionSyntax? GetRootConditionalAccessExpression(this SyntaxNode? node)
{
// Once we've walked up the entire RHS, now we continually walk up the conditional accesses until we're at
// the root. For example, if we have `a?.b` and we're on the `.b`, this will give `a?.b`. Similarly with
// `a?.b?.c` if we're on either `.b` or `.c` this will result in `a?.b?.c` (i.e. the root of this CAE
// sequence).
var current = node.GetParentConditionalAccessExpression();
while (current.IsParentKind(SyntaxKind.ConditionalAccessExpression, out ConditionalAccessExpressionSyntax? conditional) &&
conditional.WhenNotNull == current)
{
current = conditional;
}
return current;
}
public static ConditionalAccessExpressionSyntax? GetInnerMostConditionalAccessExpression(this SyntaxNode node)
{
if (!(node is ConditionalAccessExpressionSyntax))
{
return null;
}
var result = (ConditionalAccessExpressionSyntax)node;
while (result.WhenNotNull is ConditionalAccessExpressionSyntax)
{
result = (ConditionalAccessExpressionSyntax)result.WhenNotNull;
}
return result;
}
public static bool IsAsyncSupportingFunctionSyntax([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return node.IsKind(SyntaxKind.MethodDeclaration)
|| node.IsAnyLambdaOrAnonymousMethod()
|| node.IsKind(SyntaxKind.LocalFunctionStatement);
}
public static bool IsAnyLambda([NotNullWhen(returnValue: true)] this SyntaxNode? node)
{
return
node.IsKind(SyntaxKind.ParenthesizedLambdaExpression) ||
node.IsKind(SyntaxKind.SimpleLambdaExpression);
}
public static bool IsAnyLambdaOrAnonymousMethod([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsAnyLambda() || node.IsKind(SyntaxKind.AnonymousMethodExpression);
public static bool IsAnyAssignExpression(this SyntaxNode node)
=> SyntaxFacts.IsAssignmentExpression(node.Kind());
public static bool IsCompoundAssignExpression(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.CoalesceAssignmentExpression:
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
return true;
}
return false;
}
public static bool IsLeftSideOfAssignExpression([NotNullWhen(returnValue: true)] this SyntaxNode? node)
=> node.IsParentKind(SyntaxKind.SimpleAssignmentExpression, out AssignmentExpressionSyntax? assignment) &&
assignment.Left == node;
public static bool IsLeftSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
public static bool IsRightSideOfAnyAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsAnyAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Right == node;
}
public static bool IsLeftSideOfCompoundAssignExpression([NotNullWhen(true)] this SyntaxNode? node)
{
return node?.Parent != null &&
node.Parent.IsCompoundAssignExpression() &&
((AssignmentExpressionSyntax)node.Parent).Left == node;
}
/// <summary>
/// Returns the list of using directives that affect <paramref name="node"/>. The list will be returned in
/// top down order.
/// </summary>
public static IEnumerable<UsingDirectiveSyntax> GetEnclosingUsingDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Usings
.Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Usings));
}
public static IEnumerable<ExternAliasDirectiveSyntax> GetEnclosingExternAliasDirectives(this SyntaxNode node)
{
return node.GetAncestorOrThis<CompilationUnitSyntax>()!.Externs
.Concat(node.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>()
.Reverse()
.SelectMany(n => n.Externs));
}
public static bool IsUnsafeContext(this SyntaxNode node)
{
if (node.GetAncestor<UnsafeStatementSyntax>() != null)
{
return true;
}
return node.GetAncestors<MemberDeclarationSyntax>().Any(
m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword));
}
public static bool IsInStaticContext(this SyntaxNode node)
{
// this/base calls are always static.
if (node.FirstAncestorOrSelf<ConstructorInitializerSyntax>() != null)
{
return true;
}
var memberDeclaration = node.FirstAncestorOrSelf<MemberDeclarationSyntax>();
if (memberDeclaration == null)
{
return false;
}
switch (memberDeclaration.Kind())
{
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.EventDeclaration:
case SyntaxKind.IndexerDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword);
case SyntaxKind.PropertyDeclaration:
return memberDeclaration.GetModifiers().Any(SyntaxKind.StaticKeyword) ||
node.IsFoundUnder((PropertyDeclarationSyntax p) => p.Initializer);
case SyntaxKind.FieldDeclaration:
case SyntaxKind.EventFieldDeclaration:
// Inside a field one can only access static members of a type (unless it's top-level).
return !memberDeclaration.Parent.IsKind(SyntaxKind.CompilationUnit);
case SyntaxKind.DestructorDeclaration:
return false;
}
// Global statements are not a static context.
if (node.FirstAncestorOrSelf<GlobalStatementSyntax>() != null)
{
return false;
}
// any other location is considered static
return true;
}
public static BaseNamespaceDeclarationSyntax? GetInnermostNamespaceDeclarationWithUsings(this SyntaxNode contextNode)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor == null)
{
return contextNode.GetAncestorsOrThis<BaseNamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
else
{
// We are inside a using directive. In this case, we should find and return the first 'parent' namespace with usings.
var containingNamespace = usingDirectiveAncestor.GetAncestor<BaseNamespaceDeclarationSyntax>();
if (containingNamespace == null)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return null;
}
else
{
return containingNamespace.GetAncestors<BaseNamespaceDeclarationSyntax>().FirstOrDefault(n => n.Usings.Count > 0);
}
}
}
public static bool IsBreakableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.SwitchStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsContinuableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.ForStatement:
case SyntaxKind.ForEachStatement:
case SyntaxKind.ForEachVariableStatement:
return true;
}
return false;
}
public static bool IsReturnableConstruct(this SyntaxNode node)
{
switch (node.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.LocalFunctionStatement:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.ConstructorDeclaration:
case SyntaxKind.DestructorDeclaration:
case SyntaxKind.GetAccessorDeclaration:
case SyntaxKind.SetAccessorDeclaration:
case SyntaxKind.InitAccessorDeclaration:
case SyntaxKind.OperatorDeclaration:
case SyntaxKind.ConversionOperatorDeclaration:
case SyntaxKind.AddAccessorDeclaration:
case SyntaxKind.RemoveAccessorDeclaration:
return true;
}
return false;
}
public static bool SpansPreprocessorDirective<TSyntaxNode>(this IEnumerable<TSyntaxNode> list) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.SpansPreprocessorDirective(list);
[return: NotNullIfNotNull("node")]
public static TNode? ConvertToSingleLine<TNode>(this TNode? node, bool useElasticTrivia = false)
where TNode : SyntaxNode
{
if (node == null)
{
return node;
}
var rewriter = new SingleLineRewriter(useElasticTrivia);
return (TNode)rewriter.Visit(node);
}
/// <summary>
/// Returns true if the passed in node contains an interleaved pp directive.
///
/// i.e. The following returns false:
///
/// void Goo() {
/// #if true
/// #endif
/// }
///
/// #if true
/// void Goo() {
/// }
/// #endif
///
/// but these return true:
///
/// #if true
/// void Goo() {
/// #endif
/// }
///
/// void Goo() {
/// #if true
/// }
/// #endif
///
/// #if true
/// void Goo() {
/// #else
/// }
/// #endif
///
/// i.e. the method returns true if it contains a PP directive that belongs to a grouping
/// constructs (like #if/#endif or #region/#endregion), but the grouping construct isn't
/// entirely contained within the span of the node.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(syntaxNode, cancellationToken);
/// <summary>
/// Similar to <see cref="ContainsInterleavedDirective(SyntaxNode, CancellationToken)"/> except that the span to check
/// for interleaved directives can be specified separately to the node passed in.
/// </summary>
public static bool ContainsInterleavedDirective(this SyntaxNode syntaxNode, TextSpan span, CancellationToken cancellationToken)
=> CSharpSyntaxFacts.Instance.ContainsInterleavedDirective(span, syntaxNode, cancellationToken);
public static bool ContainsInterleavedDirective(
this SyntaxToken token,
TextSpan textSpan,
CancellationToken cancellationToken)
{
return
ContainsInterleavedDirective(textSpan, token.LeadingTrivia, cancellationToken) ||
ContainsInterleavedDirective(textSpan, token.TrailingTrivia, cancellationToken);
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTriviaList list,
CancellationToken cancellationToken)
{
foreach (var trivia in list)
{
if (textSpan.Contains(trivia.Span))
{
if (ContainsInterleavedDirective(textSpan, trivia, cancellationToken))
{
return true;
}
}
}
return false;
}
private static bool ContainsInterleavedDirective(
TextSpan textSpan,
SyntaxTrivia trivia,
CancellationToken cancellationToken)
{
if (trivia.HasStructure)
{
var structure = trivia.GetStructure()!;
if (trivia.GetStructure().IsKind(SyntaxKind.RegionDirectiveTrivia,
SyntaxKind.EndRegionDirectiveTrivia,
SyntaxKind.IfDirectiveTrivia,
SyntaxKind.EndIfDirectiveTrivia))
{
var match = ((DirectiveTriviaSyntax)structure).GetMatchingDirective(cancellationToken);
if (match != null)
{
var matchSpan = match.Span;
if (!textSpan.Contains(matchSpan.Start))
{
// The match for this pp directive is outside
// this node.
return true;
}
}
}
else if (trivia.GetStructure().IsKind(SyntaxKind.ElseDirectiveTrivia, SyntaxKind.ElifDirectiveTrivia))
{
var directives = ((DirectiveTriviaSyntax)structure).GetMatchingConditionalDirectives(cancellationToken);
if (directives != null && directives.Count > 0)
{
if (!textSpan.Contains(directives[0].SpanStart) ||
!textSpan.Contains(directives[directives.Count - 1].SpanStart))
{
// This else/elif belongs to a pp span that isn't
// entirely within this node.
return true;
}
}
}
}
return false;
}
/// <summary>
/// Breaks up the list of provided nodes, based on how they are interspersed with pp
/// directives, into groups. Within these groups nodes can be moved around safely, without
/// breaking any pp constructs.
/// </summary>
public static IList<IList<TSyntaxNode>> SplitNodesOnPreprocessorBoundaries<TSyntaxNode>(
this IEnumerable<TSyntaxNode> nodes,
CancellationToken cancellationToken)
where TSyntaxNode : SyntaxNode
{
var result = new List<IList<TSyntaxNode>>();
var currentGroup = new List<TSyntaxNode>();
foreach (var node in nodes)
{
var hasUnmatchedInteriorDirective = node.ContainsInterleavedDirective(cancellationToken);
var hasLeadingDirective = node.GetLeadingTrivia().Any(t => SyntaxFacts.IsPreprocessorDirective(t.Kind()));
if (hasUnmatchedInteriorDirective)
{
// we have a #if/#endif/#region/#endregion/#else/#elif in
// this node that belongs to a span of pp directives that
// is not entirely contained within the node. i.e.:
//
// void Goo() {
// #if ...
// }
//
// This node cannot be moved at all. It is in a group that
// only contains itself (and thus can never be moved).
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
result.Add(new List<TSyntaxNode> { node });
}
else if (hasLeadingDirective)
{
// We have a PP directive before us. i.e.:
//
// #if ...
// void Goo() {
//
// That means we start a new group that is contained between
// the above directive and the following directive.
// add whatever group we've built up to now. And reset the
// next group to empty.
result.Add(currentGroup);
currentGroup = new List<TSyntaxNode>();
currentGroup.Add(node);
}
else
{
// simple case. just add ourselves to the current group
currentGroup.Add(node);
}
}
// add the remainder of the final group.
result.Add(currentGroup);
// Now, filter out any empty groups.
result = result.Where(group => !group.IsEmpty()).ToList();
return result;
}
public static ImmutableArray<SyntaxTrivia> GetLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node);
public static TSyntaxNode GetNodeWithoutLeadingBlankLines<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBlankLines(node, out strippedTrivia);
public static ImmutableArray<SyntaxTrivia> GetLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node);
public static TSyntaxNode GetNodeWithoutLeadingBannerAndPreprocessorDirectives<TSyntaxNode>(this TSyntaxNode node, out ImmutableArray<SyntaxTrivia> strippedTrivia) where TSyntaxNode : SyntaxNode
=> CSharpSyntaxFacts.Instance.GetNodeWithoutLeadingBannerAndPreprocessorDirectives(node, out strippedTrivia);
public static bool IsVariableDeclaratorValue(this SyntaxNode node)
=> node.IsParentKind(SyntaxKind.EqualsValueClause, out EqualsValueClauseSyntax? equalsValue) &&
equalsValue.IsParentKind(SyntaxKind.VariableDeclarator) &&
equalsValue.Value == node;
public static BlockSyntax? FindInnermostCommonBlock(this IEnumerable<SyntaxNode> nodes)
=> nodes.FindInnermostCommonNode<BlockSyntax>();
public static IEnumerable<SyntaxNode> GetAncestorsOrThis(this SyntaxNode? node, Func<SyntaxNode, bool> predicate)
{
var current = node;
while (current != null)
{
if (predicate(current))
{
yield return current;
}
current = current.Parent;
}
}
/// <summary>
/// Returns child node or token that contains given position.
/// </summary>
/// <remarks>
/// This is a copy of <see cref="SyntaxNode.ChildThatContainsPosition"/> that also returns the index of the child node.
/// </remarks>
internal static SyntaxNodeOrToken ChildThatContainsPosition(this SyntaxNode self, int position, out int childIndex)
{
var childList = self.ChildNodesAndTokens();
var left = 0;
var right = childList.Count - 1;
while (left <= right)
{
var middle = left + ((right - left) / 2);
var node = childList[middle];
var span = node.FullSpan;
if (position < span.Start)
{
right = middle - 1;
}
else if (position >= span.End)
{
left = middle + 1;
}
else
{
childIndex = middle;
return node;
}
}
// we could check up front that index is within FullSpan,
// but we wan to optimize for the common case where position is valid.
Debug.Assert(!self.FullSpan.Contains(position), "Position is valid. How could we not find a child?");
throw new ArgumentOutOfRangeException(nameof(position));
}
public static (SyntaxToken openParen, SyntaxToken closeParen) GetParentheses(this SyntaxNode node)
{
switch (node)
{
case ParenthesizedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case MakeRefExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefTypeExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case RefValueExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CheckedExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DefaultExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case TypeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SizeOfExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CastExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case WhileStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case DoStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ForStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CommonForEachStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case UsingStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case FixedStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case LockStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case IfStatementSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case SwitchStatementSyntax n when n.OpenParenToken != default: return (n.OpenParenToken, n.CloseParenToken);
case TupleExpressionSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case CatchDeclarationSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case AttributeArgumentListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ConstructorConstraintSyntax n: return (n.OpenParenToken, n.CloseParenToken);
case ParameterListSyntax n: return (n.OpenParenToken, n.CloseParenToken);
default: return default;
}
}
public static (SyntaxToken openBracket, SyntaxToken closeBracket) GetBrackets(this SyntaxNode node)
{
switch (node)
{
case ArrayRankSpecifierSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedArgumentListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case ImplicitArrayCreationExpressionSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case AttributeListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
case BracketedParameterListSyntax n: return (n.OpenBracketToken, n.CloseBracketToken);
default: return default;
}
}
public static SyntaxTokenList GetModifiers(this SyntaxNode? member)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.Modifiers;
case AccessorDeclarationSyntax accessor: return accessor.Modifiers;
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.Modifiers;
case LocalFunctionStatementSyntax localFunction: return localFunction.Modifiers;
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.Modifiers;
}
return default;
}
public static SyntaxNode? WithModifiers(this SyntaxNode? member, SyntaxTokenList modifiers)
{
switch (member)
{
case MemberDeclarationSyntax memberDecl: return memberDecl.WithModifiers(modifiers);
case AccessorDeclarationSyntax accessor: return accessor.WithModifiers(modifiers);
case AnonymousFunctionExpressionSyntax anonymous: return anonymous.WithModifiers(modifiers);
case LocalFunctionStatementSyntax localFunction: return localFunction.WithModifiers(modifiers);
case LocalDeclarationStatementSyntax localDeclaration: return localDeclaration.WithModifiers(modifiers);
}
return null;
}
public static bool CheckTopLevel(this SyntaxNode node, TextSpan span)
{
switch (node)
{
case BlockSyntax block:
return block.ContainsInBlockBody(span);
case ArrowExpressionClauseSyntax expressionBodiedMember:
return expressionBodiedMember.ContainsInExpressionBodiedMemberBody(span);
case FieldDeclarationSyntax field:
{
foreach (var variable in field.Declaration.Variables)
{
if (variable.Initializer != null && variable.Initializer.Span.Contains(span))
{
return true;
}
}
break;
}
case GlobalStatementSyntax _:
return true;
case ConstructorInitializerSyntax constructorInitializer:
return constructorInitializer.ContainsInArgument(span);
}
return false;
}
public static bool ContainsInArgument(this ConstructorInitializerSyntax initializer, TextSpan textSpan)
{
if (initializer == null)
{
return false;
}
return initializer.ArgumentList.Arguments.Any(a => a.Span.Contains(textSpan));
}
public static bool ContainsInBlockBody(this BlockSyntax block, TextSpan textSpan)
{
if (block == null)
{
return false;
}
var blockSpan = TextSpan.FromBounds(block.OpenBraceToken.Span.End, block.CloseBraceToken.SpanStart);
return blockSpan.Contains(textSpan);
}
public static bool ContainsInExpressionBodiedMemberBody(this ArrowExpressionClauseSyntax expressionBodiedMember, TextSpan textSpan)
{
if (expressionBodiedMember == null)
{
return false;
}
var expressionBodiedMemberBody = TextSpan.FromBounds(expressionBodiedMember.Expression.SpanStart, expressionBodiedMember.Expression.Span.End);
return expressionBodiedMemberBody.Contains(textSpan);
}
public static IEnumerable<MemberDeclarationSyntax> GetMembers(this SyntaxNode? node)
{
switch (node)
{
case CompilationUnitSyntax compilation:
return compilation.Members;
case BaseNamespaceDeclarationSyntax @namespace:
return @namespace.Members;
case TypeDeclarationSyntax type:
return type.Members;
case EnumDeclarationSyntax @enum:
return @enum.Members;
}
return SpecializedCollections.EmptyEnumerable<MemberDeclarationSyntax>();
}
public static bool IsInExpressionTree(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
SemanticModel semanticModel,
[NotNullWhen(returnValue: true)] INamedTypeSymbol? expressionTypeOpt,
CancellationToken cancellationToken)
{
if (expressionTypeOpt != null)
{
for (var current = node; current != null; current = current.Parent)
{
if (current.IsAnyLambda())
{
var typeInfo = semanticModel.GetTypeInfo(current, cancellationToken);
if (expressionTypeOpt.Equals(typeInfo.ConvertedType?.OriginalDefinition))
return true;
}
else if (current is SelectOrGroupClauseSyntax ||
current is OrderingSyntax)
{
var info = semanticModel.GetSymbolInfo(current, cancellationToken);
if (TakesExpressionTree(info, expressionTypeOpt))
return true;
}
else if (current is QueryClauseSyntax queryClause)
{
var info = semanticModel.GetQueryClauseInfo(queryClause, cancellationToken);
if (TakesExpressionTree(info.CastInfo, expressionTypeOpt) ||
TakesExpressionTree(info.OperationInfo, expressionTypeOpt))
{
return true;
}
}
}
}
return false;
static bool TakesExpressionTree(SymbolInfo info, INamedTypeSymbol expressionType)
{
foreach (var symbol in info.GetAllSymbols())
{
if (symbol is IMethodSymbol method &&
method.Parameters.Length > 0 &&
expressionType.Equals(method.Parameters[0].Type?.OriginalDefinition))
{
return true;
}
}
return false;
}
}
public static bool IsInDeconstructionLeft(
[NotNullWhen(returnValue: true)] this SyntaxNode? node,
[NotNullWhen(returnValue: true)] out SyntaxNode? deconstructionLeft)
{
SyntaxNode? previous = null;
for (var current = node; current != null; current = current.Parent)
{
if ((current is AssignmentExpressionSyntax assignment && previous == assignment.Left && assignment.IsDeconstruction()) ||
(current is ForEachVariableStatementSyntax @foreach && previous == @foreach.Variable))
{
deconstructionLeft = previous;
return true;
}
if (current is StatementSyntax)
{
break;
}
previous = current;
}
deconstructionLeft = null;
return false;
}
public static bool IsTopLevelOfUsingAliasDirective(this SyntaxToken node)
=> node switch
{
{ Parent: NameEqualsSyntax { Parent: UsingDirectiveSyntax _ } } => true,
{ Parent: IdentifierNameSyntax { Parent: UsingDirectiveSyntax _ } } => true,
_ => false
};
public static T WithCommentsFrom<T>(this T node, SyntaxToken leadingToken, SyntaxToken trailingToken)
where T : SyntaxNode
=> node.WithCommentsFrom(
SyntaxNodeOrTokenExtensions.GetTrivia(leadingToken),
SyntaxNodeOrTokenExtensions.GetTrivia(trailingToken));
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxToken> leadingTokens,
IEnumerable<SyntaxToken> trailingTokens)
where T : SyntaxNode
=> node.WithCommentsFrom(leadingTokens.GetTrivia(), trailingTokens.GetTrivia());
public static T WithCommentsFrom<T>(
this T node,
IEnumerable<SyntaxTrivia> leadingTrivia,
IEnumerable<SyntaxTrivia> trailingTrivia,
params SyntaxNodeOrToken[] trailingNodesOrTokens)
where T : SyntaxNode
=> node
.WithLeadingTrivia(leadingTrivia.Concat(node.GetLeadingTrivia()).FilterComments(addElasticMarker: false))
.WithTrailingTrivia(
node.GetTrailingTrivia().Concat(SyntaxNodeOrTokenExtensions.GetTrivia(trailingNodesOrTokens).Concat(trailingTrivia)).FilterComments(addElasticMarker: false));
public static T KeepCommentsAndAddElasticMarkers<T>(this T node) where T : SyntaxNode
=> node
.WithTrailingTrivia(node.GetTrailingTrivia().FilterComments(addElasticMarker: true))
.WithLeadingTrivia(node.GetLeadingTrivia().FilterComments(addElasticMarker: true));
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/Rules/TokenBasedFormattingRule.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal sealed class TokenBasedFormattingRule : BaseFormattingRule
{
internal const string Name = "CSharp Token Based Formatting Rule";
private readonly CachedOptions _options;
public TokenBasedFormattingRule()
: this(new CachedOptions(null))
{
}
private TokenBasedFormattingRule(CachedOptions options)
{
_options = options;
}
public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options)
{
var cachedOptions = new CachedOptions(options);
if (cachedOptions == _options)
{
return this;
}
return new TokenBasedFormattingRule(cachedOptions);
}
public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
////////////////////////////////////////////////////
// brace related operations
// * { or * }
switch (currentToken.Kind())
{
case SyntaxKind.OpenBraceToken:
if (currentToken.IsInterpolation())
{
return null;
}
if (!previousToken.IsParenInParenthesizedExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
break;
case SyntaxKind.CloseBraceToken:
if (currentToken.IsInterpolation())
{
return null;
}
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// do { } while case
if (previousToken.Kind() == SyntaxKind.CloseBraceToken && currentToken.Kind() == SyntaxKind.WhileKeyword)
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// { * or } *
switch (previousToken.Kind())
{
case SyntaxKind.CloseBraceToken:
if (previousToken.IsInterpolation())
{
return null;
}
if (!previousToken.IsCloseBraceOfExpression())
{
if (!currentToken.IsKind(SyntaxKind.SemicolonToken) &&
!currentToken.IsParenInParenthesizedExpression() &&
!currentToken.IsCommaInInitializerExpression() &&
!currentToken.IsCommaInAnyArgumentsList() &&
!currentToken.IsCommaInTupleExpression() &&
!currentToken.IsParenInArgumentList() &&
!currentToken.IsDotInMemberAccess() &&
!currentToken.IsCloseParenInStatement() &&
!currentToken.IsEqualsTokenInAutoPropertyInitializers() &&
!currentToken.IsColonInCasePatternSwitchLabel() && // no newline required before colon in pattern-switch-label (ex: `case {<pattern>}:`)
!currentToken.IsColonInSwitchExpressionArm()) // no newline required before colon in switch-expression-arm (ex: `{<pattern>}: expression`)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
}
break;
case SyntaxKind.OpenBraceToken:
if (previousToken.IsInterpolation())
{
return null;
}
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
///////////////////////////////////////////////////
// statement related operations
// object and anonymous initializer "," case
if (previousToken.IsCommaInInitializerExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in switch expression arm
// ```
// e switch
// {
// pattern1: expression1, // newline with minimum of 1 line (each arm must be on its own line)
// pattern2: expression2 ...
// ```
if (previousToken.IsCommaInSwitchExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in property sub-pattern
// ```
// e is
// {
// property1: pattern1, // newline so the next line should be indented same as this one
// property2: pattern2, property3: pattern3, ... // but with minimum 0 lines so each property isn't forced to its own line
// ```
if (previousToken.IsCommaInPropertyPatternClause())
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// else * except else if case
if (previousToken.Kind() == SyntaxKind.ElseKeyword && currentToken.Kind() != SyntaxKind.IfKeyword)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in enum declarations
if (previousToken.IsCommaInEnumDeclaration())
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// : cases
if (previousToken.IsColonInSwitchLabel() ||
previousToken.IsColonInLabeledStatement())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// embedded statement
if (previousToken.Kind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
if (previousToken.Kind() == SyntaxKind.DoKeyword && previousToken.Parent.IsKind(SyntaxKind.DoStatement))
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// for (int i = 10; i < 10; i++) case
if (previousToken.IsSemicolonInForStatement())
{
return nextOperation.Invoke(in previousToken, in currentToken);
}
// ; case in the switch case statement and else condition
if (previousToken.Kind() == SyntaxKind.SemicolonToken &&
(currentToken.Kind() == SyntaxKind.CaseKeyword || currentToken.Kind() == SyntaxKind.DefaultKeyword || currentToken.Kind() == SyntaxKind.ElseKeyword))
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// ; * or ; * for using directive
if (previousToken.Kind() == SyntaxKind.SemicolonToken)
{
return AdjustNewLinesAfterSemicolonToken(previousToken, currentToken);
}
// attribute case ] *
// force to next line for top level attributes
if (previousToken.Kind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
{
var attributeOwner = previousToken.Parent?.Parent;
if (attributeOwner is CompilationUnitSyntax ||
attributeOwner is MemberDeclarationSyntax ||
attributeOwner is AccessorDeclarationSyntax)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
private AdjustNewLinesOperation AdjustNewLinesAfterSemicolonToken(
SyntaxToken previousToken, SyntaxToken currentToken)
{
// between anything that isn't a using directive, we don't touch newlines after a semicolon
if (!(previousToken.Parent is UsingDirectiveSyntax previousUsing))
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
// if the user is separating using-groups, and we're between two usings, and these
// usings *should* be separated, then do so (if the usings were already properly
// sorted).
if (_options.SeparateImportDirectiveGroups &&
currentToken.Parent is UsingDirectiveSyntax currentUsing &&
UsingsAndExternAliasesOrganizer.NeedsGrouping(previousUsing, currentUsing))
{
RoslynDebug.AssertNotNull(currentUsing.Parent);
var usings = GetUsings(currentUsing.Parent);
if (usings.IsSorted(UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance) ||
usings.IsSorted(UsingsAndExternAliasesDirectiveComparer.NormalInstance))
{
// Force at least one blank line here.
return CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.PreserveLines);
}
}
// For all other cases where we have a using-directive, just make sure it's followed by
// a new-line.
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
private static SyntaxList<UsingDirectiveSyntax> GetUsings(SyntaxNode node)
=> node switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.Usings,
NamespaceDeclarationSyntax namespaceDecl => namespaceDecl.Usings,
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation)
{
//////////////////////////////////////////////////////
// ";" related operations
if (currentToken.Kind() == SyntaxKind.SemicolonToken)
{
// ; ;
if (previousToken.Kind() == SyntaxKind.SemicolonToken)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ) ; with embedded statement case
if (previousToken.Kind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * ;
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// omitted tokens case
if (previousToken.Kind() == SyntaxKind.OmittedArraySizeExpressionToken ||
previousToken.Kind() == SyntaxKind.OmittedTypeArgumentToken ||
currentToken.Kind() == SyntaxKind.OmittedArraySizeExpressionToken ||
currentToken.Kind() == SyntaxKind.OmittedTypeArgumentToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
if (previousToken.IsKind(SyntaxKind.CloseBracketToken) &&
previousToken.Parent.IsKind(SyntaxKind.AttributeList) &&
previousToken.Parent.IsParentKind(SyntaxKind.Parameter))
{
if (currentToken.IsKind(SyntaxKind.OpenBracketToken))
{
// multiple attribute on parameter stick together
// void M([...][...]
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
else
{
// attribute is spaced from parameter type
// void M([...] int
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// extension method on tuple type
// M(this (
if (currentToken.Kind() == SyntaxKind.OpenParenToken &&
previousToken.Kind() == SyntaxKind.ThisKeyword)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// new (int, int)[]
if (currentToken.Kind() == SyntaxKind.OpenParenToken &&
previousToken.Kind() == SyntaxKind.NewKeyword &&
previousToken.Parent.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ArrayCreationExpression))
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// some * "(" cases
if (currentToken.Kind() == SyntaxKind.OpenParenToken)
{
if (previousToken.Kind() == SyntaxKind.IdentifierToken ||
previousToken.Kind() == SyntaxKind.DefaultKeyword ||
previousToken.Kind() == SyntaxKind.BaseKeyword ||
previousToken.Kind() == SyntaxKind.ThisKeyword ||
previousToken.Kind() == SyntaxKind.NewKeyword ||
previousToken.IsGenericGreaterThanToken() ||
currentToken.IsParenInArgumentList())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// empty () or []
if (previousToken.ParenOrBracketContainsNothing(currentToken))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// attribute case
// , [
if (previousToken.Kind() == SyntaxKind.CommaToken && currentToken.Kind() == SyntaxKind.OpenBracketToken && currentToken.Parent is AttributeListSyntax)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ] *
if (previousToken.Kind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
{
// preserving dev10 behavior, in dev10 we didn't touch space after attribute
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
}
// * )
// * ]
// * ,
// * .
// * ->
switch (currentToken.Kind())
{
case SyntaxKind.CloseParenToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.CommaToken:
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * [
if (currentToken.IsKind(SyntaxKind.OpenBracketToken) &&
!previousToken.IsOpenBraceOrCommaOfObjectInitializer())
{
if (previousToken.IsOpenBraceOfAccessorList() ||
previousToken.IsLastTokenOfNode<AccessorDeclarationSyntax>())
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
else
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// case * :
// default:
// <label> :
// { Property1.Property2: ... }
if (currentToken.IsKind(SyntaxKind.ColonToken))
{
if (currentToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.CasePatternSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.LabeledStatement,
SyntaxKind.AttributeTargetSpecifier,
SyntaxKind.NameColon,
SyntaxKind.ExpressionColon,
SyntaxKind.SwitchExpressionArm))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// [cast expression] * case
if (previousToken.Parent is CastExpressionSyntax &&
previousToken.Kind() == SyntaxKind.CloseParenToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// generic name
if (previousToken.Parent.IsKind(SyntaxKind.TypeArgumentList, SyntaxKind.TypeParameterList, SyntaxKind.FunctionPointerType))
{
// generic name < *
if (previousToken.Kind() == SyntaxKind.LessThanToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// generic name > *
if (previousToken.Kind() == SyntaxKind.GreaterThanToken && currentToken.Kind() == SyntaxKind.GreaterThanToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// generic name * < or * >
if ((currentToken.Kind() == SyntaxKind.LessThanToken || currentToken.Kind() == SyntaxKind.GreaterThanToken) &&
currentToken.Parent.IsKind(SyntaxKind.TypeArgumentList, SyntaxKind.TypeParameterList))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ++ * or -- *
if ((previousToken.Kind() == SyntaxKind.PlusPlusToken || previousToken.Kind() == SyntaxKind.MinusMinusToken) &&
previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * ++ or * --
if ((currentToken.Kind() == SyntaxKind.PlusPlusToken || currentToken.Kind() == SyntaxKind.MinusMinusToken) &&
currentToken.Parent is PostfixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// For spacing between the identifier and the conditional operator
if (currentToken.IsKind(SyntaxKind.QuestionToken) && currentToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// nullable
if (currentToken.Kind() == SyntaxKind.QuestionToken &&
currentToken.Parent.IsKind(SyntaxKind.NullableType, SyntaxKind.ClassConstraint))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// No space between an array type and ?
if (currentToken.IsKind(SyntaxKind.QuestionToken) &&
previousToken.Parent?.IsParentKind(SyntaxKind.ArrayType) == true)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// suppress warning operator: null! or x! or x++! or x[i]! or (x)! or ...
if (currentToken.Kind() == SyntaxKind.ExclamationToken &&
currentToken.Parent.IsKind(SyntaxKind.SuppressNullableWarningExpression))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// pointer case for regular pointers
if (currentToken.Kind() == SyntaxKind.AsteriskToken && currentToken.Parent is PointerTypeSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// unary asterisk operator (PointerIndirectionExpression)
if (previousToken.Kind() == SyntaxKind.AsteriskToken && previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ( * or ) * or [ * or ] * or . * or -> *
switch (previousToken.Kind())
{
case SyntaxKind.OpenParenToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
case SyntaxKind.CloseParenToken:
case SyntaxKind.CloseBracketToken:
var space = (previousToken.Kind() == currentToken.Kind()) ? 0 : 1;
return CreateAdjustSpacesOperation(space, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// +1 or -1
if (previousToken.IsPlusOrMinusExpression() && !currentToken.IsPlusOrMinusExpression())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// +- or -+
if (previousToken.IsPlusOrMinusExpression() && currentToken.IsPlusOrMinusExpression() &&
previousToken.Kind() != currentToken.Kind())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ! *, except where ! is the suppress nullable warning operator
if (previousToken.Kind() == SyntaxKind.ExclamationToken
&& !previousToken.Parent.IsKind(SyntaxKind.SuppressNullableWarningExpression))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ~ * case
if (previousToken.Kind() == SyntaxKind.TildeToken && (previousToken.Parent is PrefixUnaryExpressionSyntax || previousToken.Parent is DestructorDeclarationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// & * case
if (previousToken.Kind() == SyntaxKind.AmpersandToken &&
previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * :: or :: * case
if (previousToken.Kind() == SyntaxKind.ColonColonToken || currentToken.Kind() == SyntaxKind.ColonColonToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
private readonly struct CachedOptions : IEquatable<CachedOptions>
{
public readonly bool SeparateImportDirectiveGroups;
public CachedOptions(AnalyzerConfigOptions? options)
{
SeparateImportDirectiveGroups = GetOptionOrDefault(options, GenerationOptions.SeparateImportDirectiveGroups);
}
public static bool operator ==(CachedOptions left, CachedOptions right)
=> left.Equals(right);
public static bool operator !=(CachedOptions left, CachedOptions right)
=> !(left == right);
private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, PerLanguageOption2<T> option)
{
if (options is null)
return option.DefaultValue;
return options.GetOption(option);
}
public override bool Equals(object? obj)
=> obj is CachedOptions options && Equals(options);
public bool Equals(CachedOptions other)
{
return SeparateImportDirectiveGroups == other.SeparateImportDirectiveGroups;
}
public override int GetHashCode()
{
var hashCode = 0;
hashCode = (hashCode << 1) + (SeparateImportDirectiveGroups ? 1 : 0);
return hashCode;
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Formatting
{
internal sealed class TokenBasedFormattingRule : BaseFormattingRule
{
internal const string Name = "CSharp Token Based Formatting Rule";
private readonly CachedOptions _options;
public TokenBasedFormattingRule()
: this(new CachedOptions(null))
{
}
private TokenBasedFormattingRule(CachedOptions options)
{
_options = options;
}
public override AbstractFormattingRule WithOptions(AnalyzerConfigOptions options)
{
var cachedOptions = new CachedOptions(options);
if (cachedOptions == _options)
{
return this;
}
return new TokenBasedFormattingRule(cachedOptions);
}
public override AdjustNewLinesOperation? GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation)
{
////////////////////////////////////////////////////
// brace related operations
// * { or * }
switch (currentToken.Kind())
{
case SyntaxKind.OpenBraceToken:
if (currentToken.IsInterpolation())
{
return null;
}
if (!previousToken.IsParenInParenthesizedExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
break;
case SyntaxKind.CloseBraceToken:
if (currentToken.IsInterpolation())
{
return null;
}
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// do { } while case
if (previousToken.Kind() == SyntaxKind.CloseBraceToken && currentToken.Kind() == SyntaxKind.WhileKeyword)
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// { * or } *
switch (previousToken.Kind())
{
case SyntaxKind.CloseBraceToken:
if (previousToken.IsInterpolation())
{
return null;
}
if (!previousToken.IsCloseBraceOfExpression())
{
if (!currentToken.IsKind(SyntaxKind.SemicolonToken) &&
!currentToken.IsParenInParenthesizedExpression() &&
!currentToken.IsCommaInInitializerExpression() &&
!currentToken.IsCommaInAnyArgumentsList() &&
!currentToken.IsCommaInTupleExpression() &&
!currentToken.IsParenInArgumentList() &&
!currentToken.IsDotInMemberAccess() &&
!currentToken.IsCloseParenInStatement() &&
!currentToken.IsEqualsTokenInAutoPropertyInitializers() &&
!currentToken.IsColonInCasePatternSwitchLabel() && // no newline required before colon in pattern-switch-label (ex: `case {<pattern>}:`)
!currentToken.IsColonInSwitchExpressionArm()) // no newline required before colon in switch-expression-arm (ex: `{<pattern>}: expression`)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
}
break;
case SyntaxKind.OpenBraceToken:
if (previousToken.IsInterpolation())
{
return null;
}
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
///////////////////////////////////////////////////
// statement related operations
// object and anonymous initializer "," case
if (previousToken.IsCommaInInitializerExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in switch expression arm
// ```
// e switch
// {
// pattern1: expression1, // newline with minimum of 1 line (each arm must be on its own line)
// pattern2: expression2 ...
// ```
if (previousToken.IsCommaInSwitchExpression())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in property sub-pattern
// ```
// e is
// {
// property1: pattern1, // newline so the next line should be indented same as this one
// property2: pattern2, property3: pattern3, ... // but with minimum 0 lines so each property isn't forced to its own line
// ```
if (previousToken.IsCommaInPropertyPatternClause())
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// else * except else if case
if (previousToken.Kind() == SyntaxKind.ElseKeyword && currentToken.Kind() != SyntaxKind.IfKeyword)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// , * in enum declarations
if (previousToken.IsCommaInEnumDeclaration())
{
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
// : cases
if (previousToken.IsColonInSwitchLabel() ||
previousToken.IsColonInLabeledStatement())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// embedded statement
if (previousToken.Kind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
if (previousToken.Kind() == SyntaxKind.DoKeyword && previousToken.Parent.IsKind(SyntaxKind.DoStatement))
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// for (int i = 10; i < 10; i++) case
if (previousToken.IsSemicolonInForStatement())
{
return nextOperation.Invoke(in previousToken, in currentToken);
}
// ; case in the switch case statement and else condition
if (previousToken.Kind() == SyntaxKind.SemicolonToken &&
(currentToken.Kind() == SyntaxKind.CaseKeyword || currentToken.Kind() == SyntaxKind.DefaultKeyword || currentToken.Kind() == SyntaxKind.ElseKeyword))
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
// ; * or ; * for using directive
if (previousToken.Kind() == SyntaxKind.SemicolonToken)
{
return AdjustNewLinesAfterSemicolonToken(previousToken, currentToken);
}
// attribute case ] *
// force to next line for top level attributes
if (previousToken.Kind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
{
var attributeOwner = previousToken.Parent?.Parent;
if (attributeOwner is CompilationUnitSyntax ||
attributeOwner is MemberDeclarationSyntax ||
attributeOwner is AccessorDeclarationSyntax)
{
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
private AdjustNewLinesOperation AdjustNewLinesAfterSemicolonToken(
SyntaxToken previousToken, SyntaxToken currentToken)
{
// between anything that isn't a using directive, we don't touch newlines after a semicolon
if (!(previousToken.Parent is UsingDirectiveSyntax previousUsing))
return CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines);
// if the user is separating using-groups, and we're between two usings, and these
// usings *should* be separated, then do so (if the usings were already properly
// sorted).
if (_options.SeparateImportDirectiveGroups &&
currentToken.Parent is UsingDirectiveSyntax currentUsing &&
UsingsAndExternAliasesOrganizer.NeedsGrouping(previousUsing, currentUsing))
{
RoslynDebug.AssertNotNull(currentUsing.Parent);
var usings = GetUsings(currentUsing.Parent);
if (usings.IsSorted(UsingsAndExternAliasesDirectiveComparer.SystemFirstInstance) ||
usings.IsSorted(UsingsAndExternAliasesDirectiveComparer.NormalInstance))
{
// Force at least one blank line here.
return CreateAdjustNewLinesOperation(2, AdjustNewLinesOption.PreserveLines);
}
}
// For all other cases where we have a using-directive, just make sure it's followed by
// a new-line.
return CreateAdjustNewLinesOperation(1, AdjustNewLinesOption.PreserveLines);
}
private static SyntaxList<UsingDirectiveSyntax> GetUsings(SyntaxNode node)
=> node switch
{
CompilationUnitSyntax compilationUnit => compilationUnit.Usings,
BaseNamespaceDeclarationSyntax namespaceDecl => namespaceDecl.Usings,
_ => throw ExceptionUtilities.UnexpectedValue(node.Kind()),
};
public override AdjustSpacesOperation? GetAdjustSpacesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustSpacesOperation nextOperation)
{
//////////////////////////////////////////////////////
// ";" related operations
if (currentToken.Kind() == SyntaxKind.SemicolonToken)
{
// ; ;
if (previousToken.Kind() == SyntaxKind.SemicolonToken)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ) ; with embedded statement case
if (previousToken.Kind() == SyntaxKind.CloseParenToken && previousToken.Parent.IsEmbeddedStatementOwnerWithCloseParen())
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * ;
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// omitted tokens case
if (previousToken.Kind() == SyntaxKind.OmittedArraySizeExpressionToken ||
previousToken.Kind() == SyntaxKind.OmittedTypeArgumentToken ||
currentToken.Kind() == SyntaxKind.OmittedArraySizeExpressionToken ||
currentToken.Kind() == SyntaxKind.OmittedTypeArgumentToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
if (previousToken.IsKind(SyntaxKind.CloseBracketToken) &&
previousToken.Parent.IsKind(SyntaxKind.AttributeList) &&
previousToken.Parent.IsParentKind(SyntaxKind.Parameter))
{
if (currentToken.IsKind(SyntaxKind.OpenBracketToken))
{
// multiple attribute on parameter stick together
// void M([...][...]
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
else
{
// attribute is spaced from parameter type
// void M([...] int
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// extension method on tuple type
// M(this (
if (currentToken.Kind() == SyntaxKind.OpenParenToken &&
previousToken.Kind() == SyntaxKind.ThisKeyword)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// new (int, int)[]
if (currentToken.Kind() == SyntaxKind.OpenParenToken &&
previousToken.Kind() == SyntaxKind.NewKeyword &&
previousToken.Parent.IsKind(SyntaxKind.ObjectCreationExpression, SyntaxKind.ArrayCreationExpression))
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// some * "(" cases
if (currentToken.Kind() == SyntaxKind.OpenParenToken)
{
if (previousToken.Kind() == SyntaxKind.IdentifierToken ||
previousToken.Kind() == SyntaxKind.DefaultKeyword ||
previousToken.Kind() == SyntaxKind.BaseKeyword ||
previousToken.Kind() == SyntaxKind.ThisKeyword ||
previousToken.Kind() == SyntaxKind.NewKeyword ||
previousToken.IsGenericGreaterThanToken() ||
currentToken.IsParenInArgumentList())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// empty () or []
if (previousToken.ParenOrBracketContainsNothing(currentToken))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// attribute case
// , [
if (previousToken.Kind() == SyntaxKind.CommaToken && currentToken.Kind() == SyntaxKind.OpenBracketToken && currentToken.Parent is AttributeListSyntax)
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ] *
if (previousToken.Kind() == SyntaxKind.CloseBracketToken && previousToken.Parent is AttributeListSyntax)
{
// preserving dev10 behavior, in dev10 we didn't touch space after attribute
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.PreserveSpaces);
}
// * )
// * ]
// * ,
// * .
// * ->
switch (currentToken.Kind())
{
case SyntaxKind.CloseParenToken:
case SyntaxKind.CloseBracketToken:
case SyntaxKind.CommaToken:
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * [
if (currentToken.IsKind(SyntaxKind.OpenBracketToken) &&
!previousToken.IsOpenBraceOrCommaOfObjectInitializer())
{
if (previousToken.IsOpenBraceOfAccessorList() ||
previousToken.IsLastTokenOfNode<AccessorDeclarationSyntax>())
{
return CreateAdjustSpacesOperation(1, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
else
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// case * :
// default:
// <label> :
// { Property1.Property2: ... }
if (currentToken.IsKind(SyntaxKind.ColonToken))
{
if (currentToken.Parent.IsKind(SyntaxKind.CaseSwitchLabel,
SyntaxKind.CasePatternSwitchLabel,
SyntaxKind.DefaultSwitchLabel,
SyntaxKind.LabeledStatement,
SyntaxKind.AttributeTargetSpecifier,
SyntaxKind.NameColon,
SyntaxKind.ExpressionColon,
SyntaxKind.SwitchExpressionArm))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// [cast expression] * case
if (previousToken.Parent is CastExpressionSyntax &&
previousToken.Kind() == SyntaxKind.CloseParenToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// generic name
if (previousToken.Parent.IsKind(SyntaxKind.TypeArgumentList, SyntaxKind.TypeParameterList, SyntaxKind.FunctionPointerType))
{
// generic name < *
if (previousToken.Kind() == SyntaxKind.LessThanToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// generic name > *
if (previousToken.Kind() == SyntaxKind.GreaterThanToken && currentToken.Kind() == SyntaxKind.GreaterThanToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
}
// generic name * < or * >
if ((currentToken.Kind() == SyntaxKind.LessThanToken || currentToken.Kind() == SyntaxKind.GreaterThanToken) &&
currentToken.Parent.IsKind(SyntaxKind.TypeArgumentList, SyntaxKind.TypeParameterList))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ++ * or -- *
if ((previousToken.Kind() == SyntaxKind.PlusPlusToken || previousToken.Kind() == SyntaxKind.MinusMinusToken) &&
previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * ++ or * --
if ((currentToken.Kind() == SyntaxKind.PlusPlusToken || currentToken.Kind() == SyntaxKind.MinusMinusToken) &&
currentToken.Parent is PostfixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// For spacing between the identifier and the conditional operator
if (currentToken.IsKind(SyntaxKind.QuestionToken) && currentToken.Parent.IsKind(SyntaxKind.ConditionalAccessExpression))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// nullable
if (currentToken.Kind() == SyntaxKind.QuestionToken &&
currentToken.Parent.IsKind(SyntaxKind.NullableType, SyntaxKind.ClassConstraint))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// No space between an array type and ?
if (currentToken.IsKind(SyntaxKind.QuestionToken) &&
previousToken.Parent?.IsParentKind(SyntaxKind.ArrayType) == true)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpaces);
}
// suppress warning operator: null! or x! or x++! or x[i]! or (x)! or ...
if (currentToken.Kind() == SyntaxKind.ExclamationToken &&
currentToken.Parent.IsKind(SyntaxKind.SuppressNullableWarningExpression))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// pointer case for regular pointers
if (currentToken.Kind() == SyntaxKind.AsteriskToken && currentToken.Parent is PointerTypeSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// unary asterisk operator (PointerIndirectionExpression)
if (previousToken.Kind() == SyntaxKind.AsteriskToken && previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ( * or ) * or [ * or ] * or . * or -> *
switch (previousToken.Kind())
{
case SyntaxKind.OpenParenToken:
case SyntaxKind.OpenBracketToken:
case SyntaxKind.DotToken:
case SyntaxKind.MinusGreaterThanToken:
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
case SyntaxKind.CloseParenToken:
case SyntaxKind.CloseBracketToken:
var space = (previousToken.Kind() == currentToken.Kind()) ? 0 : 1;
return CreateAdjustSpacesOperation(space, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// +1 or -1
if (previousToken.IsPlusOrMinusExpression() && !currentToken.IsPlusOrMinusExpression())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// +- or -+
if (previousToken.IsPlusOrMinusExpression() && currentToken.IsPlusOrMinusExpression() &&
previousToken.Kind() != currentToken.Kind())
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ! *, except where ! is the suppress nullable warning operator
if (previousToken.Kind() == SyntaxKind.ExclamationToken
&& !previousToken.Parent.IsKind(SyntaxKind.SuppressNullableWarningExpression))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// ~ * case
if (previousToken.Kind() == SyntaxKind.TildeToken && (previousToken.Parent is PrefixUnaryExpressionSyntax || previousToken.Parent is DestructorDeclarationSyntax))
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// & * case
if (previousToken.Kind() == SyntaxKind.AmpersandToken &&
previousToken.Parent is PrefixUnaryExpressionSyntax)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
// * :: or :: * case
if (previousToken.Kind() == SyntaxKind.ColonColonToken || currentToken.Kind() == SyntaxKind.ColonColonToken)
{
return CreateAdjustSpacesOperation(0, AdjustSpacesOption.ForceSpacesIfOnSingleLine);
}
return nextOperation.Invoke(in previousToken, in currentToken);
}
private readonly struct CachedOptions : IEquatable<CachedOptions>
{
public readonly bool SeparateImportDirectiveGroups;
public CachedOptions(AnalyzerConfigOptions? options)
{
SeparateImportDirectiveGroups = GetOptionOrDefault(options, GenerationOptions.SeparateImportDirectiveGroups);
}
public static bool operator ==(CachedOptions left, CachedOptions right)
=> left.Equals(right);
public static bool operator !=(CachedOptions left, CachedOptions right)
=> !(left == right);
private static T GetOptionOrDefault<T>(AnalyzerConfigOptions? options, PerLanguageOption2<T> option)
{
if (options is null)
return option.DefaultValue;
return options.GetOption(option);
}
public override bool Equals(object? obj)
=> obj is CachedOptions options && Equals(options);
public bool Equals(CachedOptions other)
{
return SeparateImportDirectiveGroups == other.SeparateImportDirectiveGroups;
}
public override int GetHashCode()
{
var hashCode = 0;
hashCode = (hashCode << 1) + (SeparateImportDirectiveGroups ? 1 : 0);
return hashCode;
}
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/CompilationUnitSyntaxExtensions.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;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class CompilationUnitSyntaxExtensions
{
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, Document document, CancellationToken cancellationToken)
=> CanAddUsingDirectives(contextNode, document.CanAddImportsInHiddenRegions(), cancellationToken);
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, bool allowInHiddenRegions, CancellationToken cancellationToken)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor?.Parent is CompilationUnitSyntax)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return false;
}
if (!allowInHiddenRegions && contextNode.SyntaxTree.HasHiddenRegions())
{
var namespaceDeclaration = contextNode.GetInnermostNamespaceDeclarationWithUsings();
var root = (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
var span = GetUsingsSpan(root, namespaceDeclaration);
if (contextNode.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken))
{
return false;
}
}
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return true;
}
private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, NamespaceDeclarationSyntax? namespaceDeclaration)
{
if (namespaceDeclaration != null)
{
var usings = namespaceDeclaration.Usings;
var start = usings.First().SpanStart;
var end = usings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var rootUsings = root.Usings;
if (rootUsings.Any())
{
var start = rootUsings.First().SpanStart;
var end = rootUsings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var start = 0;
var end = root.Members.Any()
? root.Members.First().GetFirstToken().Span.End
: root.Span.End;
return TextSpan.FromBounds(start, end);
}
}
}
public static CompilationUnitSyntax AddUsingDirective(
this CompilationUnitSyntax root,
UsingDirectiveSyntax usingDirective,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
return root.AddUsingDirectives(new[] { usingDirective }, contextNode, placeSystemNamespaceFirst, annotations);
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (!usingDirectives.Any())
{
return root;
}
var firstOuterNamespaceWithUsings = contextNode.GetInnermostNamespaceDeclarationWithUsings();
if (firstOuterNamespaceWithUsings == null)
{
return root.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
}
else
{
var newNamespace = firstOuterNamespaceWithUsings.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
return root.ReplaceNode(firstOuterNamespaceWithUsings, newNamespace);
}
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (usingDirectives.Count == 0)
{
return root;
}
var usings = AddUsingDirectives(root, usingDirectives);
// Keep usings sorted if they were originally sorted.
usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst);
if (root.Externs.Count == 0)
{
root = AddImportHelpers.MoveTrivia(
CSharpSyntaxFacts.Instance, root, root.Usings, usings);
}
return root.WithUsings(
usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToSyntaxList());
}
private static List<UsingDirectiveSyntax> AddUsingDirectives(
CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives)
{
// We need to try and not place the using inside of a directive if possible.
var usings = new List<UsingDirectiveSyntax>();
var endOfList = root.Usings.Count - 1;
var startOfLastDirective = -1;
var endOfLastDirective = -1;
for (var i = 0; i < root.Usings.Count; i++)
{
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.IfDirectiveTrivia)))
{
startOfLastDirective = i;
}
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)))
{
endOfLastDirective = i;
}
}
// if the entire using is in a directive or there is a using list at the end outside of the directive add the using at the end,
// else place it before the last directive.
usings.AddRange(root.Usings);
if ((startOfLastDirective == 0 && (endOfLastDirective == endOfList || endOfLastDirective == -1)) ||
(startOfLastDirective == -1 && endOfLastDirective == -1) ||
(endOfLastDirective != endOfList && endOfLastDirective != -1))
{
usings.AddRange(usingDirectives);
}
else
{
usings.InsertRange(startOfLastDirective, usingDirectives);
}
return usings;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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;
using Microsoft.CodeAnalysis.AddImports;
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp.Extensions
{
internal static class CompilationUnitSyntaxExtensions
{
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, Document document, CancellationToken cancellationToken)
=> CanAddUsingDirectives(contextNode, document.CanAddImportsInHiddenRegions(), cancellationToken);
public static bool CanAddUsingDirectives(this SyntaxNode contextNode, bool allowInHiddenRegions, CancellationToken cancellationToken)
{
var usingDirectiveAncestor = contextNode.GetAncestor<UsingDirectiveSyntax>();
if (usingDirectiveAncestor?.Parent is CompilationUnitSyntax)
{
// We are inside a top level using directive (i.e. one that's directly in the compilation unit).
return false;
}
if (!allowInHiddenRegions && contextNode.SyntaxTree.HasHiddenRegions())
{
var namespaceDeclaration = contextNode.GetInnermostNamespaceDeclarationWithUsings();
var root = (CompilationUnitSyntax)contextNode.SyntaxTree.GetRoot(cancellationToken);
var span = GetUsingsSpan(root, namespaceDeclaration);
if (contextNode.SyntaxTree.OverlapsHiddenPosition(span, cancellationToken))
{
return false;
}
}
if (cancellationToken.IsCancellationRequested)
{
return false;
}
return true;
}
private static TextSpan GetUsingsSpan(CompilationUnitSyntax root, BaseNamespaceDeclarationSyntax? namespaceDeclaration)
{
if (namespaceDeclaration != null)
{
var usings = namespaceDeclaration.Usings;
var start = usings.First().SpanStart;
var end = usings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var rootUsings = root.Usings;
if (rootUsings.Any())
{
var start = rootUsings.First().SpanStart;
var end = rootUsings.Last().Span.End;
return TextSpan.FromBounds(start, end);
}
else
{
var start = 0;
var end = root.Members.Any()
? root.Members.First().GetFirstToken().Span.End
: root.Span.End;
return TextSpan.FromBounds(start, end);
}
}
}
public static CompilationUnitSyntax AddUsingDirective(
this CompilationUnitSyntax root,
UsingDirectiveSyntax usingDirective,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
return root.AddUsingDirectives(new[] { usingDirective }, contextNode, placeSystemNamespaceFirst, annotations);
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
SyntaxNode contextNode,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (!usingDirectives.Any())
{
return root;
}
var firstOuterNamespaceWithUsings = contextNode.GetInnermostNamespaceDeclarationWithUsings();
if (firstOuterNamespaceWithUsings == null)
{
return root.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
}
else
{
var newNamespace = firstOuterNamespaceWithUsings.AddUsingDirectives(usingDirectives, placeSystemNamespaceFirst, annotations);
return root.ReplaceNode(firstOuterNamespaceWithUsings, newNamespace);
}
}
public static CompilationUnitSyntax AddUsingDirectives(
this CompilationUnitSyntax root,
IList<UsingDirectiveSyntax> usingDirectives,
bool placeSystemNamespaceFirst,
params SyntaxAnnotation[] annotations)
{
if (usingDirectives.Count == 0)
{
return root;
}
var usings = AddUsingDirectives(root, usingDirectives);
// Keep usings sorted if they were originally sorted.
usings.SortUsingDirectives(root.Usings, placeSystemNamespaceFirst);
if (root.Externs.Count == 0)
{
root = AddImportHelpers.MoveTrivia(
CSharpSyntaxFacts.Instance, root, root.Usings, usings);
}
return root.WithUsings(
usings.Select(u => u.WithAdditionalAnnotations(annotations)).ToSyntaxList());
}
private static List<UsingDirectiveSyntax> AddUsingDirectives(
CompilationUnitSyntax root, IList<UsingDirectiveSyntax> usingDirectives)
{
// We need to try and not place the using inside of a directive if possible.
var usings = new List<UsingDirectiveSyntax>();
var endOfList = root.Usings.Count - 1;
var startOfLastDirective = -1;
var endOfLastDirective = -1;
for (var i = 0; i < root.Usings.Count; i++)
{
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.IfDirectiveTrivia)))
{
startOfLastDirective = i;
}
if (root.Usings[i].GetLeadingTrivia().Any(trivia => trivia.IsKind(SyntaxKind.EndIfDirectiveTrivia)))
{
endOfLastDirective = i;
}
}
// if the entire using is in a directive or there is a using list at the end outside of the directive add the using at the end,
// else place it before the last directive.
usings.AddRange(root.Usings);
if ((startOfLastDirective == 0 && (endOfLastDirective == endOfList || endOfLastDirective == -1)) ||
(startOfLastDirective == -1 && endOfLastDirective == -1) ||
(endOfLastDirective != endOfList && endOfLastDirective != -1))
{
usings.AddRange(usingDirectives);
}
else
{
usings.InsertRange(startOfLastDirective, usingDirectives);
}
return usings;
}
}
}
| 1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/LiveShare/Impl/LSPSDKInitializeHandler.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 System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare
{
/// <summary>
/// Handle the initialize request and report the capabilities of the server.
/// TODO Once the client side code is migrated to LSP client, this can be removed.
/// </summary>
[ExportLspRequestHandler(LiveShareConstants.RoslynLSPSDKContractName, LSP.Methods.InitializeName)]
internal class LSPSDKInitializeHandler : ILspRequestHandler<LSP.InitializeParams, LSP.InitializeResult, Solution>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LSPSDKInitializeHandler()
{
}
public Task<LSP.InitializeResult> HandleAsync(LSP.InitializeParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken)
{
var result = new LSP.InitializeResult
{
Capabilities = new LSP.ServerCapabilities()
};
return Task.FromResult(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.
#nullable disable
using System;
using System.ComponentModel.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LiveShare.LanguageServices;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.VisualStudio.LanguageServices.LiveShare
{
/// <summary>
/// Handle the initialize request and report the capabilities of the server.
/// TODO Once the client side code is migrated to LSP client, this can be removed.
/// </summary>
[ExportLspRequestHandler(LiveShareConstants.RoslynLSPSDKContractName, LSP.Methods.InitializeName)]
internal class LSPSDKInitializeHandler : ILspRequestHandler<LSP.InitializeParams, LSP.InitializeResult, Solution>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LSPSDKInitializeHandler()
{
}
public Task<LSP.InitializeResult> HandleAsync(LSP.InitializeParams request, RequestContext<Solution> requestContext, CancellationToken cancellationToken)
{
var result = new LSP.InitializeResult
{
Capabilities = new LSP.ServerCapabilities()
};
return Task.FromResult(result);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualBasic/Impl/LanguageService/IVbCompilerService.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
''' <summary>
''' A dummy interface with the same GUID as the legacy SID_SVisualBasicCompiler. This is needed so the managed
''' package framework can properly expose the service, since we need _some_ type to give for the ProvideService
''' attribute. We need our package to have a different GUID than this service, but they need to be implemented by
''' the same object since some project systems (Venus) assume we are implemented this way.
''' </summary>
<Guid(Guids.VisualBasicCompilerServiceIdString)>
Friend Interface IVbCompilerService
End Interface
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic
''' <summary>
''' A dummy interface with the same GUID as the legacy SID_SVisualBasicCompiler. This is needed so the managed
''' package framework can properly expose the service, since we need _some_ type to give for the ProvideService
''' attribute. We need our package to have a different GUID than this service, but they need to be implemented by
''' the same object since some project systems (Venus) assume we are implemented this way.
''' </summary>
<Guid(Guids.VisualBasicCompilerServiceIdString)>
Friend Interface IVbCompilerService
End Interface
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Syntax/Syntax/SyntaxDiffingTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SyntaxDiffingTests
{
[Fact]
public void TestDiffEmptyVersusClass()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("");
var newTree = SyntaxFactory.ParseSyntaxTree("class C { }");
// it should be all new
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(newTree.GetCompilationUnitRoot().FullSpan, spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("class C { }", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNameChanged()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = SyntaxFactory.ParseSyntaxTree("class B { }");
// since most tokens are automatically interned we should see only the name tokens change
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
var decl = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0];
Assert.Equal(decl.Identifier.Span, spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(6, 1), changes[0].Span);
Assert.Equal("B", changes[0].NewText);
}
[Fact]
public void TestDiffTwoClassesWithBothNamesChanged()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { } class B { }");
var newTree = SyntaxFactory.ParseSyntaxTree("class C { } class D { }");
// since most tokens are automatically interned we should see only the name tokens change
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(2, spans.Count);
var decl1 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0];
Assert.Equal(decl1.Identifier.Span, spans[0]);
var decl2 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[1];
Assert.Equal(decl2.Identifier.Span, spans[1]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(2, changes.Count);
Assert.Equal(new TextSpan(6, 1), changes[0].Span);
Assert.Equal("C", changes[0].NewText);
Assert.Equal(new TextSpan(18, 1), changes[1].Span);
Assert.Equal("D", changes[1].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(0, 6), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("class ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted2()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class A ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(0, 8), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("class A ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted3()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class A { }");
// new tree appears to have two duplicate (similar) copies of the same declarations (indistinguishable)
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(11, 11), spans[0]); // its going to pick one of the two spans.
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(11, 0), changes[0].Span);
Assert.Equal("class A { }", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted4()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class A { } ");
// new tree appears to have two almost duplicate (similar) copies of the same declarations, except the
// second (original) one is a closer match
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(10, 12), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(10, 0), changes[0].Span);
Assert.Equal("} class A { ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewNamespaceEnclosing()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "namespace N { ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(0, 14), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("namespace N { ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewMemberInserted()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(10, "int X; ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(10, 7), spans[0]); // int X;
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(10, 0), changes[0].Span);
Assert.Equal("int X; ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithMemberRemoved()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }");
var newTree = oldTree.WithRemoveAt(10, 7);
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(0, spans.Count);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(10, 7), changes[0].Span);
Assert.Equal("", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithMemberRemovedDeep()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }");
var newTree = oldTree.WithRemoveAt(24, 7);
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(0, spans.Count);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(24, 7), changes[0].Span);
Assert.Equal("", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithMemberNameRemoved()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }");
var newTree = oldTree.WithRemoveAt(14, 1);
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(0, spans.Count);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(14, 1), changes[0].Span);
Assert.Equal("", changes[0].NewText);
}
[Fact]
public void TestDiffClassChangedToStruct()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }");
var newTree = oldTree.WithReplaceFirst("class", "struct");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(14, 6), spans[0]); // 'struct'
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(14, 5), changes[0].Span);
Assert.Equal("struct", changes[0].NewText);
}
[Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")]
public void TestQualifyWithThis()
{
var original = @"
class C
{
int Sign;
void F()
{
string x = @""namespace Namespace
{
class Type
{
void Goo()
{
int x = 1 "" + Sign + @"" "" + Sign + @""3;
}
}
}
"";
}
}";
var oldTree = SyntaxFactory.ParseSyntaxTree(original);
var root = oldTree.GetRoot();
var indexText = "Sign +";
// Expected behavior: Qualifying identifier 'Sign' with 'this.' and doing a diff between trees
// should return a single text change with 'this.' as added text.
// Works as expected for last index
var index = original.LastIndexOf(indexText, StringComparison.Ordinal);
TestQualifyWithThisCore(root, index);
// Doesn't work as expected for first index.
// It returns 2 changes with add followed by delete,
// causing the 2 isolated edits of adding "this." to seem conflicting edits, even though they are not.
// See https://github.com/dotnet/roslyn/issues/320 for details.
index = original.IndexOf(indexText, StringComparison.Ordinal);
TestQualifyWithThisCore(root, index);
}
private void TestQualifyWithThisCore(SyntaxNode root, int index)
{
var oldTree = root.SyntaxTree;
var span = new TextSpan(index, 4);
var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax;
Assert.NotNull(node);
Assert.Equal("Sign", node.Identifier.ValueText);
var leadingTrivia = node.GetLeadingTrivia();
var newNode = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ThisExpression(),
node.WithoutLeadingTrivia())
.WithLeadingTrivia(leadingTrivia);
var newRoot = root.ReplaceNode(node, newNode);
var newTree = newRoot.SyntaxTree;
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal("this.", changes[0].NewText);
}
[Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")]
public void TestReplaceWithBuiltInType()
{
var original = @"
using System;
using System.Collections.Generic;
public class TestClass
{
public void TestMethod()
{
var dictionary = new Dictionary<Object, Object>();
dictionary[new Object()] = new Object();
}
}";
var oldTree = SyntaxFactory.ParseSyntaxTree(original);
var root = oldTree.GetRoot();
var indexText = "Object";
// Expected behavior: Replacing identifier 'Object' with 'object' and doing a diff between trees
// should return a single text change for character replace.
// Works as expected for first index
var index = original.IndexOf(indexText, StringComparison.Ordinal);
TestReplaceWithBuiltInTypeCore(root, index);
// Works as expected for last index
index = original.LastIndexOf(indexText, StringComparison.Ordinal);
TestReplaceWithBuiltInTypeCore(root, index);
// Doesn't work as expected for the third index.
// It returns 2 changes with add followed by delete,
// causing the 2 isolated edits to seem conflicting edits, even though they are not.
// See https://github.com/dotnet/roslyn/issues/320 for details.
indexText = "Object()";
index = original.IndexOf(indexText, StringComparison.Ordinal);
TestReplaceWithBuiltInTypeCore(root, index);
}
private void TestReplaceWithBuiltInTypeCore(SyntaxNode root, int index)
{
var oldTree = root.SyntaxTree;
var span = new TextSpan(index, 6);
var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax;
Assert.NotNull(node);
Assert.Equal("Object", node.Identifier.ValueText);
var leadingTrivia = node.GetLeadingTrivia();
var newNode = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword))
.WithLeadingTrivia(leadingTrivia);
var newRoot = root.ReplaceNode(node, newNode);
var newTree = newRoot.SyntaxTree;
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal("o", changes[0].NewText);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SyntaxDiffingTests
{
[Fact]
public void TestDiffEmptyVersusClass()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("");
var newTree = SyntaxFactory.ParseSyntaxTree("class C { }");
// it should be all new
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(newTree.GetCompilationUnitRoot().FullSpan, spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("class C { }", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNameChanged()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = SyntaxFactory.ParseSyntaxTree("class B { }");
// since most tokens are automatically interned we should see only the name tokens change
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
var decl = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0];
Assert.Equal(decl.Identifier.Span, spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(6, 1), changes[0].Span);
Assert.Equal("B", changes[0].NewText);
}
[Fact]
public void TestDiffTwoClassesWithBothNamesChanged()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { } class B { }");
var newTree = SyntaxFactory.ParseSyntaxTree("class C { } class D { }");
// since most tokens are automatically interned we should see only the name tokens change
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(2, spans.Count);
var decl1 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[0];
Assert.Equal(decl1.Identifier.Span, spans[0]);
var decl2 = (TypeDeclarationSyntax)(newTree.GetCompilationUnitRoot()).Members[1];
Assert.Equal(decl2.Identifier.Span, spans[1]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(2, changes.Count);
Assert.Equal(new TextSpan(6, 1), changes[0].Span);
Assert.Equal("C", changes[0].NewText);
Assert.Equal(new TextSpan(18, 1), changes[1].Span);
Assert.Equal("D", changes[1].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(0, 6), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("class ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted2()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class A ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(0, 8), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("class A ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted3()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class A { }");
// new tree appears to have two duplicate (similar) copies of the same declarations (indistinguishable)
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(11, 11), spans[0]); // its going to pick one of the two spans.
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(11, 0), changes[0].Span);
Assert.Equal("class A { }", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewClassStarted4()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "class A { } ");
// new tree appears to have two almost duplicate (similar) copies of the same declarations, except the
// second (original) one is a closer match
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(10, 12), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(10, 0), changes[0].Span);
Assert.Equal("} class A { ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewNamespaceEnclosing()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(0, "namespace N { ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(0, 14), spans[0]);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(0, 0), changes[0].Span);
Assert.Equal("namespace N { ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithNewMemberInserted()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { }");
var newTree = oldTree.WithInsertAt(10, "int X; ");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(10, 7), spans[0]); // int X;
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(10, 0), changes[0].Span);
Assert.Equal("int X; ", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithMemberRemoved()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }");
var newTree = oldTree.WithRemoveAt(10, 7);
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(0, spans.Count);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(10, 7), changes[0].Span);
Assert.Equal("", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithMemberRemovedDeep()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }");
var newTree = oldTree.WithRemoveAt(24, 7);
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(0, spans.Count);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(24, 7), changes[0].Span);
Assert.Equal("", changes[0].NewText);
}
[Fact]
public void TestDiffClassWithMemberNameRemoved()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("class A { int X; }");
var newTree = oldTree.WithRemoveAt(14, 1);
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(0, spans.Count);
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(14, 1), changes[0].Span);
Assert.Equal("", changes[0].NewText);
}
[Fact]
public void TestDiffClassChangedToStruct()
{
var oldTree = SyntaxFactory.ParseSyntaxTree("namespace N { class A { int X; } }");
var newTree = oldTree.WithReplaceFirst("class", "struct");
var spans = newTree.GetChangedSpans(oldTree);
Assert.NotNull(spans);
Assert.Equal(1, spans.Count);
Assert.Equal(new TextSpan(14, 6), spans[0]); // 'struct'
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal(new TextSpan(14, 5), changes[0].Span);
Assert.Equal("struct", changes[0].NewText);
}
[Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")]
public void TestQualifyWithThis()
{
var original = @"
class C
{
int Sign;
void F()
{
string x = @""namespace Namespace
{
class Type
{
void Goo()
{
int x = 1 "" + Sign + @"" "" + Sign + @""3;
}
}
}
"";
}
}";
var oldTree = SyntaxFactory.ParseSyntaxTree(original);
var root = oldTree.GetRoot();
var indexText = "Sign +";
// Expected behavior: Qualifying identifier 'Sign' with 'this.' and doing a diff between trees
// should return a single text change with 'this.' as added text.
// Works as expected for last index
var index = original.LastIndexOf(indexText, StringComparison.Ordinal);
TestQualifyWithThisCore(root, index);
// Doesn't work as expected for first index.
// It returns 2 changes with add followed by delete,
// causing the 2 isolated edits of adding "this." to seem conflicting edits, even though they are not.
// See https://github.com/dotnet/roslyn/issues/320 for details.
index = original.IndexOf(indexText, StringComparison.Ordinal);
TestQualifyWithThisCore(root, index);
}
private void TestQualifyWithThisCore(SyntaxNode root, int index)
{
var oldTree = root.SyntaxTree;
var span = new TextSpan(index, 4);
var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax;
Assert.NotNull(node);
Assert.Equal("Sign", node.Identifier.ValueText);
var leadingTrivia = node.GetLeadingTrivia();
var newNode = SyntaxFactory.MemberAccessExpression(
SyntaxKind.SimpleMemberAccessExpression,
SyntaxFactory.ThisExpression(),
node.WithoutLeadingTrivia())
.WithLeadingTrivia(leadingTrivia);
var newRoot = root.ReplaceNode(node, newNode);
var newTree = newRoot.SyntaxTree;
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal("this.", changes[0].NewText);
}
[Fact, WorkItem(463, "https://github.com/dotnet/roslyn/issues/463")]
public void TestReplaceWithBuiltInType()
{
var original = @"
using System;
using System.Collections.Generic;
public class TestClass
{
public void TestMethod()
{
var dictionary = new Dictionary<Object, Object>();
dictionary[new Object()] = new Object();
}
}";
var oldTree = SyntaxFactory.ParseSyntaxTree(original);
var root = oldTree.GetRoot();
var indexText = "Object";
// Expected behavior: Replacing identifier 'Object' with 'object' and doing a diff between trees
// should return a single text change for character replace.
// Works as expected for first index
var index = original.IndexOf(indexText, StringComparison.Ordinal);
TestReplaceWithBuiltInTypeCore(root, index);
// Works as expected for last index
index = original.LastIndexOf(indexText, StringComparison.Ordinal);
TestReplaceWithBuiltInTypeCore(root, index);
// Doesn't work as expected for the third index.
// It returns 2 changes with add followed by delete,
// causing the 2 isolated edits to seem conflicting edits, even though they are not.
// See https://github.com/dotnet/roslyn/issues/320 for details.
indexText = "Object()";
index = original.IndexOf(indexText, StringComparison.Ordinal);
TestReplaceWithBuiltInTypeCore(root, index);
}
private void TestReplaceWithBuiltInTypeCore(SyntaxNode root, int index)
{
var oldTree = root.SyntaxTree;
var span = new TextSpan(index, 6);
var node = root.FindNode(span, getInnermostNodeForTie: true) as SimpleNameSyntax;
Assert.NotNull(node);
Assert.Equal("Object", node.Identifier.ValueText);
var leadingTrivia = node.GetLeadingTrivia();
var newNode = SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.ObjectKeyword))
.WithLeadingTrivia(leadingTrivia);
var newRoot = root.ReplaceNode(node, newNode);
var newTree = newRoot.SyntaxTree;
var changes = newTree.GetChanges(oldTree);
Assert.NotNull(changes);
Assert.Equal(1, changes.Count);
Assert.Equal("o", changes[0].NewText);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/AddFileBanner/AbstractAddFileBannerCodeRefactoringProvider.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.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddFileBanner
{
internal abstract class AbstractAddFileBannerCodeRefactoringProvider : CodeRefactoringProvider
{
protected abstract bool IsCommentStartCharacter(char ch);
protected abstract SyntaxTrivia CreateTrivia(SyntaxTrivia trivia, string text);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
if (!span.IsEmpty)
{
return;
}
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (document.Project.AnalyzerOptions.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
&& !string.IsNullOrEmpty(fileHeaderTemplate))
{
// If we have a defined file header template, allow the analyzer and code fix to handle it
return;
}
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var position = span.Start;
var firstToken = root.GetFirstToken();
if (!firstToken.FullSpan.IntersectsWith(position))
{
return;
}
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var banner = syntaxFacts.GetFileBanner(root);
if (banner.Length > 0)
{
// Already has a banner.
return;
}
// Process the other documents in this document's project. Look at the
// ones that we can get a root from (without having to parse). Then
// look at the ones we'd need to parse.
var siblingDocumentsAndRoots =
document.Project.Documents
.Where(d => d != document)
.Select(d =>
{
d.TryGetSyntaxRoot(out var siblingRoot);
return (document: d, root: siblingRoot);
})
.OrderBy((t1, t2) => (t1.root != null) == (t2.root != null) ? 0 : t1.root != null ? -1 : 1);
foreach (var (siblingDocument, siblingRoot) in siblingDocumentsAndRoots)
{
cancellationToken.ThrowIfCancellationRequested();
var siblingBanner = await TryGetBannerAsync(siblingDocument, siblingRoot, cancellationToken).ConfigureAwait(false);
if (siblingBanner.Length > 0 && !siblingDocument.IsGeneratedCode(cancellationToken))
{
context.RegisterRefactoring(
new MyCodeAction(_ => AddBannerAsync(document, root, siblingDocument, siblingBanner)),
new Text.TextSpan(position, length: 0));
return;
}
}
}
private Task<Document> AddBannerAsync(
Document document, SyntaxNode root,
Document siblingDocument, ImmutableArray<SyntaxTrivia> banner)
{
banner = UpdateEmbeddedFileNames(siblingDocument, document, banner);
var newRoot = root.WithPrependedLeadingTrivia(new SyntaxTriviaList(banner));
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
/// <summary>
/// Looks at <paramref name="banner"/> to see if it contains the name of <paramref name="sourceDocument"/>
/// in it. If so, those names will be replaced with <paramref name="destinationDocument"/>'s name.
/// </summary>
private ImmutableArray<SyntaxTrivia> UpdateEmbeddedFileNames(
Document sourceDocument, Document destinationDocument, ImmutableArray<SyntaxTrivia> banner)
{
var sourceName = IOUtilities.PerformIO(() => Path.GetFileName(sourceDocument.FilePath));
var destinationName = IOUtilities.PerformIO(() => Path.GetFileName(destinationDocument.FilePath));
if (string.IsNullOrEmpty(sourceName) || string.IsNullOrEmpty(destinationName))
{
return banner;
}
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var result);
foreach (var trivia in banner)
{
var updated = CreateTrivia(trivia, trivia.ToFullString().Replace(sourceName, destinationName));
result.Add(updated);
}
return result.ToImmutable();
}
private async Task<ImmutableArray<SyntaxTrivia>> TryGetBannerAsync(
Document document, SyntaxNode root, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// If we have a tree already for this document, then just check to see
// if it has a banner.
if (root != null)
{
return syntaxFacts.GetFileBanner(root);
}
// Didn't have a tree. Don't want to parse the file if we can avoid it.
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (text.Length == 0 || !IsCommentStartCharacter(text[0]))
{
// Didn't start with a comment character, don't bother looking at
// this file.
return ImmutableArray<SyntaxTrivia>.Empty;
}
var token = syntaxFacts.ParseToken(text.ToString());
return syntaxFacts.GetFileBanner(token);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CodeFixesResources.Add_file_header, createChangedDocument, nameof(CodeFixesResources.Add_file_header))
{
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddFileBanner
{
internal abstract class AbstractAddFileBannerCodeRefactoringProvider : CodeRefactoringProvider
{
protected abstract bool IsCommentStartCharacter(char ch);
protected abstract SyntaxTrivia CreateTrivia(SyntaxTrivia trivia, string text);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
if (!span.IsEmpty)
{
return;
}
var tree = await document.GetRequiredSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
if (document.Project.AnalyzerOptions.TryGetEditorConfigOption<string>(CodeStyleOptions2.FileHeaderTemplate, tree, out var fileHeaderTemplate)
&& !string.IsNullOrEmpty(fileHeaderTemplate))
{
// If we have a defined file header template, allow the analyzer and code fix to handle it
return;
}
var root = await tree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var position = span.Start;
var firstToken = root.GetFirstToken();
if (!firstToken.FullSpan.IntersectsWith(position))
{
return;
}
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
var banner = syntaxFacts.GetFileBanner(root);
if (banner.Length > 0)
{
// Already has a banner.
return;
}
// Process the other documents in this document's project. Look at the
// ones that we can get a root from (without having to parse). Then
// look at the ones we'd need to parse.
var siblingDocumentsAndRoots =
document.Project.Documents
.Where(d => d != document)
.Select(d =>
{
d.TryGetSyntaxRoot(out var siblingRoot);
return (document: d, root: siblingRoot);
})
.OrderBy((t1, t2) => (t1.root != null) == (t2.root != null) ? 0 : t1.root != null ? -1 : 1);
foreach (var (siblingDocument, siblingRoot) in siblingDocumentsAndRoots)
{
cancellationToken.ThrowIfCancellationRequested();
var siblingBanner = await TryGetBannerAsync(siblingDocument, siblingRoot, cancellationToken).ConfigureAwait(false);
if (siblingBanner.Length > 0 && !siblingDocument.IsGeneratedCode(cancellationToken))
{
context.RegisterRefactoring(
new MyCodeAction(_ => AddBannerAsync(document, root, siblingDocument, siblingBanner)),
new Text.TextSpan(position, length: 0));
return;
}
}
}
private Task<Document> AddBannerAsync(
Document document, SyntaxNode root,
Document siblingDocument, ImmutableArray<SyntaxTrivia> banner)
{
banner = UpdateEmbeddedFileNames(siblingDocument, document, banner);
var newRoot = root.WithPrependedLeadingTrivia(new SyntaxTriviaList(banner));
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
/// <summary>
/// Looks at <paramref name="banner"/> to see if it contains the name of <paramref name="sourceDocument"/>
/// in it. If so, those names will be replaced with <paramref name="destinationDocument"/>'s name.
/// </summary>
private ImmutableArray<SyntaxTrivia> UpdateEmbeddedFileNames(
Document sourceDocument, Document destinationDocument, ImmutableArray<SyntaxTrivia> banner)
{
var sourceName = IOUtilities.PerformIO(() => Path.GetFileName(sourceDocument.FilePath));
var destinationName = IOUtilities.PerformIO(() => Path.GetFileName(destinationDocument.FilePath));
if (string.IsNullOrEmpty(sourceName) || string.IsNullOrEmpty(destinationName))
{
return banner;
}
using var _ = ArrayBuilder<SyntaxTrivia>.GetInstance(out var result);
foreach (var trivia in banner)
{
var updated = CreateTrivia(trivia, trivia.ToFullString().Replace(sourceName, destinationName));
result.Add(updated);
}
return result.ToImmutable();
}
private async Task<ImmutableArray<SyntaxTrivia>> TryGetBannerAsync(
Document document, SyntaxNode root, CancellationToken cancellationToken)
{
var syntaxFacts = document.GetRequiredLanguageService<ISyntaxFactsService>();
// If we have a tree already for this document, then just check to see
// if it has a banner.
if (root != null)
{
return syntaxFacts.GetFileBanner(root);
}
// Didn't have a tree. Don't want to parse the file if we can avoid it.
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (text.Length == 0 || !IsCommentStartCharacter(text[0]))
{
// Didn't start with a comment character, don't bother looking at
// this file.
return ImmutableArray<SyntaxTrivia>.Empty;
}
var token = syntaxFacts.ParseToken(text.ToString());
return syntaxFacts.GetFileBanner(token);
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CodeFixesResources.Add_file_header, createChangedDocument, nameof(CodeFixesResources.Add_file_header))
{
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/VisualBasic/Tests/NewLines/MultipleBlankLines/MultipleBlankLinesTests.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.CodeStyle
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.NewLines.MultipleBlankLines.VisualBasicMultipleBlankLinesDiagnosticAnalyzer,
Microsoft.CodeAnalysis.NewLines.MultipleBlankLines.MultipleBlankLinesCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.NewLines.MultipleBlankLines
Public Class MultipleBlankLinesTests
Private Shared Async Function TestWithOptionOn(testCode As String, fixedCode As String) As Task
Dim test = New VerifyVB.Test() With
{
.TestCode = testCode,
.FixedCode = fixedCode
}
test.Options.Add(CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSilentEnforcement)
Await test.RunAsync()
End Function
<Fact>
Public Async Function TestOneBlankLineAtTopOfFile() As Task
Dim code =
"
' comment"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAtTopOfFile() As Task
Dim code =
"[||]
' comment"
Dim fixedCode =
"
' comment"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestTwoBlankLineAtTopOfFile_NotWithOptionOff() As Task
Dim code =
"
' comment"
Await New VerifyVB.Test() With
{
.TestCode = code,
.FixedCode = code
}.RunAsync()
End Function
<Fact>
Public Async Function TestThreeBlankLineAtTopOfFile() As Task
Dim code =
"[||]
' comment"
Dim fixedCode =
"
' comment"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAtTopOfFile() As Task
Dim code =
"[||]
' comment"
Dim fixedCode =
"
' comment"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestOneBlankLineAtTopOfEmptyFile() As Task
Dim code =
"
"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLinesAtTopOfEmptyFile() As Task
Dim code =
"[||]
"
Dim fixedCode =
"
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLinesAtTopOfEmptyFile() As Task
Dim code =
"[||]
"
Dim fixedCode =
"
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLinesAtTopOfEmptyFile() As Task
Dim code =
"[||]
"
Dim fixedCode =
"
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAtEndOfFile_1() As Task
Dim code =
"Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestNoBlankLineAtEndOfFile_2() As Task
Dim code =
"Class C
End Class
"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
[||]
"
Dim fixedCode =
"Class C
End Class
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
[||]
"
Dim fixedCode =
"Class C
End Class
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
[||]
"
Dim fixedCode =
"Class C
End Class
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineBetweenTokens() As Task
Dim code =
"Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineBetweenTokens() As Task
Dim code =
"Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineBetweenTokens() As Task
Dim code =
"Class C
[||]
End Class"
Dim fixedCode =
"Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineBetweenTokens() As Task
Dim code =
"Class C
[||]
End Class"
Dim fixedCode =
"Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineBetweenTokens() As Task
Dim code =
"Class C
[||]
End Class"
Dim fixedCode =
"Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
[||]
End Class"
Dim fixedCode =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
[||]
End Class"
Dim fixedCode =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
[||]
End Class"
Dim fixedCode =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
[||]
End Class"
Dim fixedCode =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
[||]
End Class"
Dim fixedCode =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
[||]
End Class"
Dim fixedCode =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
[||]
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
[||]
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
[||]
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAllConstructs() As Task
Dim code =
"''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAllConstructs() As Task
Dim code =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAllConstructs() As Task
Dim code =
"[||]
''' <summary/>
'
#Const X = 0
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAllConstructs() As Task
Dim code =
"[||]
''' <summary/>
'
#Const X = 0
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAllConstructs() As Task
Dim code =
"[||]
''' <summary/>
'
#Const X = 0
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
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.CodeStyle
Imports VerifyVB = Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions.VisualBasicCodeFixVerifier(Of
Microsoft.CodeAnalysis.VisualBasic.NewLines.MultipleBlankLines.VisualBasicMultipleBlankLinesDiagnosticAnalyzer,
Microsoft.CodeAnalysis.NewLines.MultipleBlankLines.MultipleBlankLinesCodeFixProvider)
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.NewLines.MultipleBlankLines
Public Class MultipleBlankLinesTests
Private Shared Async Function TestWithOptionOn(testCode As String, fixedCode As String) As Task
Dim test = New VerifyVB.Test() With
{
.TestCode = testCode,
.FixedCode = fixedCode
}
test.Options.Add(CodeStyleOptions2.AllowMultipleBlankLines, CodeStyleOptions2.FalseWithSilentEnforcement)
Await test.RunAsync()
End Function
<Fact>
Public Async Function TestOneBlankLineAtTopOfFile() As Task
Dim code =
"
' comment"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAtTopOfFile() As Task
Dim code =
"[||]
' comment"
Dim fixedCode =
"
' comment"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestTwoBlankLineAtTopOfFile_NotWithOptionOff() As Task
Dim code =
"
' comment"
Await New VerifyVB.Test() With
{
.TestCode = code,
.FixedCode = code
}.RunAsync()
End Function
<Fact>
Public Async Function TestThreeBlankLineAtTopOfFile() As Task
Dim code =
"[||]
' comment"
Dim fixedCode =
"
' comment"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAtTopOfFile() As Task
Dim code =
"[||]
' comment"
Dim fixedCode =
"
' comment"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestOneBlankLineAtTopOfEmptyFile() As Task
Dim code =
"
"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLinesAtTopOfEmptyFile() As Task
Dim code =
"[||]
"
Dim fixedCode =
"
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLinesAtTopOfEmptyFile() As Task
Dim code =
"[||]
"
Dim fixedCode =
"
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLinesAtTopOfEmptyFile() As Task
Dim code =
"[||]
"
Dim fixedCode =
"
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAtEndOfFile_1() As Task
Dim code =
"Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestNoBlankLineAtEndOfFile_2() As Task
Dim code =
"Class C
End Class
"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
[||]
"
Dim fixedCode =
"Class C
End Class
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
[||]
"
Dim fixedCode =
"Class C
End Class
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAtEndOfFile() As Task
Dim code =
"Class C
End Class
[||]
"
Dim fixedCode =
"Class C
End Class
"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineBetweenTokens() As Task
Dim code =
"Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineBetweenTokens() As Task
Dim code =
"Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineBetweenTokens() As Task
Dim code =
"Class C
[||]
End Class"
Dim fixedCode =
"Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineBetweenTokens() As Task
Dim code =
"Class C
[||]
End Class"
Dim fixedCode =
"Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineBetweenTokens() As Task
Dim code =
"Class C
[||]
End Class"
Dim fixedCode =
"Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
[||]
End Class"
Dim fixedCode =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
[||]
End Class"
Dim fixedCode =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAfterComment() As Task
Dim code =
"Class C
' comment
[||]
End Class"
Dim fixedCode =
"Class C
' comment
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
[||]
End Class"
Dim fixedCode =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
[||]
End Class"
Dim fixedCode =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAfterDirective() As Task
Dim code =
"Class C
#Const X = 0
[||]
End Class"
Dim fixedCode =
"Class C
#Const X = 0
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
[||]
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
[||]
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAfterDocComment() As Task
Dim code =
"
''' <summary/>
[||]
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestNoBlankLineAllConstructs() As Task
Dim code =
"''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestOneBlankLineAllConstructs() As Task
Dim code =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, code)
End Function
<Fact>
Public Async Function TestTwoBlankLineAllConstructs() As Task
Dim code =
"[||]
''' <summary/>
'
#Const X = 0
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestThreeBlankLineAllConstructs() As Task
Dim code =
"[||]
''' <summary/>
'
#Const X = 0
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
<Fact>
Public Async Function TestFourBlankLineAllConstructs() As Task
Dim code =
"[||]
''' <summary/>
'
#Const X = 0
Class C
End Class"
Dim fixedCode =
"
''' <summary/>
'
#Const X = 0
Class C
End Class"
Await TestWithOptionOn(code, fixedCode)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Semantics/TypeInference/Graph.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.Diagnostics
Imports System.Linq
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class TypeArgumentInference
Private Class GraphNode(Of TGraphNode As GraphNode(Of TGraphNode))
Public ReadOnly Graph As Graph(Of TGraphNode)
Public IsAddedToVertices As Boolean
Public ReadOnly IncomingEdges As ArrayBuilder(Of TGraphNode)
Public ReadOnly OutgoingEdges As ArrayBuilder(Of TGraphNode)
Public AlgorithmData As GraphAlgorithmData(Of TGraphNode)
Protected Sub New(graph As Graph(Of TGraphNode))
Me.Graph = graph
Me.IsAddedToVertices = False
Me.IncomingEdges = New ArrayBuilder(Of TGraphNode)()
Me.OutgoingEdges = New ArrayBuilder(Of TGraphNode)()
End Sub
End Class
Private Enum DFSColor As Byte
None
Grey
Black
End Enum
Private Structure GraphAlgorithmData(Of TGraphNode As GraphNode(Of TGraphNode))
' DFS specific fields
Public Color As DFSColor
' Used for quick lookup of which strongly connected component this node is in.
Public StronglyConnectedComponent As StronglyConnectedComponent(Of TGraphNode)
End Structure
Private Class StronglyConnectedComponent(Of TGraphNode As GraphNode(Of TGraphNode))
Inherits GraphNode(Of StronglyConnectedComponent(Of TGraphNode))
Public ReadOnly ChildNodes As ArrayBuilder(Of TGraphNode)
Public Sub New(graph As Graph(Of StronglyConnectedComponent(Of TGraphNode)))
MyBase.New(graph)
ChildNodes = New ArrayBuilder(Of TGraphNode)()
End Sub
End Class
Private Class Graph(Of TGraphNode As GraphNode(Of TGraphNode))
Public ReadOnly Vertices As ArrayBuilder(Of TGraphNode)
Public Sub New()
Vertices = New ArrayBuilder(Of TGraphNode)()
End Sub
Public Sub AddEdge(
source As TGraphNode,
target As TGraphNode
)
AddNode(source)
AddNode(target)
source.OutgoingEdges.Add(target)
target.IncomingEdges.Add(source)
End Sub
Public Sub AddNode(
node As TGraphNode
)
Debug.Assert(node.Graph Is Me)
If Not node.IsAddedToVertices Then
Vertices.Add(node)
node.IsAddedToVertices = True
End If
End Sub
Public Sub RemoveEdge(
source As TGraphNode,
target As TGraphNode
)
Debug.Assert(Contains(source))
Debug.Assert(Contains(target))
Remove(source.OutgoingEdges, target)
Remove(target.IncomingEdges, source)
End Sub
Private Shared Sub Remove(list As ArrayBuilder(Of TGraphNode), toRemove As TGraphNode)
Dim lastIndex As Integer = list.Count - 1
For i As Integer = 0 To lastIndex Step 1
If list(i) Is toRemove Then
If i < lastIndex Then
list(i) = list(lastIndex)
End If
list.Clip(lastIndex)
Return
End If
Next
Throw ExceptionUtilities.Unreachable
End Sub
Public Function BuildStronglyConnectedComponents() As Graph(Of StronglyConnectedComponent(Of TGraphNode))
Dim sccGraph As New Graph(Of StronglyConnectedComponent(Of TGraphNode))()
' The first three steps are implementing Kosaraju's algorithm of finding
' the strongly connected components of a directed graph.
' Step 1: Perform regular Dfs and build a list with the deepest node last.
Dim orderedList = ArrayBuilder(Of TGraphNode).GetInstance()
Dfs(orderedList)
' Step 2: Reset graph algorithm Data
For Each current As TGraphNode In orderedList
current.AlgorithmData = New GraphAlgorithmData(Of TGraphNode)()
Next
' Step 3: Walk the nodes and place each tree in the forest in a separate node.
For Each current As TGraphNode In orderedList
If current.AlgorithmData.Color = DFSColor.None Then
Dim sccNode As New StronglyConnectedComponent(Of TGraphNode)(sccGraph)
CollectSccChildren(current, sccNode)
sccGraph.AddNode(sccNode)
End If
Next
orderedList.Free()
orderedList = Nothing
' Step 4: Link incoming and outgoing edges.
For Each sccNode As StronglyConnectedComponent(Of TGraphNode) In sccGraph.Vertices
For Each innerNodeIterCurrent As TGraphNode In sccNode.ChildNodes
For Each innerOutGoingInterCurrent As TGraphNode In innerNodeIterCurrent.OutgoingEdges
Dim target As StronglyConnectedComponent(Of TGraphNode) = innerOutGoingInterCurrent.AlgorithmData.StronglyConnectedComponent
' Don't create self-edges.
If sccNode IsNot target Then
sccGraph.AddEdge(sccNode, target)
End If
Next
Next
Next
Return sccGraph
End Function
Private Sub CollectSccChildren(
node As TGraphNode,
sccNode As StronglyConnectedComponent(Of TGraphNode)
)
node.AlgorithmData.Color = DFSColor.Grey
For Each current As TGraphNode In node.IncomingEdges
If current.AlgorithmData.Color = DFSColor.None Then
CollectSccChildren(current, sccNode)
End If
Next
node.AlgorithmData.Color = DFSColor.Black
Debug.Assert(node.AlgorithmData.StronglyConnectedComponent Is Nothing)
sccNode.ChildNodes.Add(node)
node.AlgorithmData.StronglyConnectedComponent = sccNode
End Sub
Public Sub TopoSort(resultList As ArrayBuilder(Of TGraphNode))
Dfs(resultList)
End Sub
Private Sub Dfs(resultList As ArrayBuilder(Of TGraphNode))
For Each current In Vertices
current.AlgorithmData = New GraphAlgorithmData(Of TGraphNode)()
Next
Dim oldListSize = resultList.Count
resultList.AddMany(Nothing, Vertices.Count)
Dim newListSize = resultList.Count
Dim insertAt As Integer = newListSize - 1
For Each current As TGraphNode In Vertices
If current.AlgorithmData.Color = DFSColor.None Then
DfsVisit(current, resultList, insertAt)
End If
Next
Debug.Assert(insertAt = oldListSize - 1)
End Sub
Private Sub DfsVisit(
node As TGraphNode,
resultList As ArrayBuilder(Of TGraphNode),
ByRef insertAt As Integer
)
node.AlgorithmData.Color = DFSColor.Grey
For Each current As TGraphNode In node.OutgoingEdges
If current.AlgorithmData.Color = DFSColor.None Then
DfsVisit(current, resultList, insertAt)
End If
Next
node.AlgorithmData.Color = DFSColor.Black
resultList(insertAt) = node
insertAt -= 1
End Sub
Private Function Contains(node As TGraphNode) As Boolean
Return node.Graph Is Me AndAlso node.IsAddedToVertices
End Function
End Class
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Diagnostics
Imports System.Linq
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class TypeArgumentInference
Private Class GraphNode(Of TGraphNode As GraphNode(Of TGraphNode))
Public ReadOnly Graph As Graph(Of TGraphNode)
Public IsAddedToVertices As Boolean
Public ReadOnly IncomingEdges As ArrayBuilder(Of TGraphNode)
Public ReadOnly OutgoingEdges As ArrayBuilder(Of TGraphNode)
Public AlgorithmData As GraphAlgorithmData(Of TGraphNode)
Protected Sub New(graph As Graph(Of TGraphNode))
Me.Graph = graph
Me.IsAddedToVertices = False
Me.IncomingEdges = New ArrayBuilder(Of TGraphNode)()
Me.OutgoingEdges = New ArrayBuilder(Of TGraphNode)()
End Sub
End Class
Private Enum DFSColor As Byte
None
Grey
Black
End Enum
Private Structure GraphAlgorithmData(Of TGraphNode As GraphNode(Of TGraphNode))
' DFS specific fields
Public Color As DFSColor
' Used for quick lookup of which strongly connected component this node is in.
Public StronglyConnectedComponent As StronglyConnectedComponent(Of TGraphNode)
End Structure
Private Class StronglyConnectedComponent(Of TGraphNode As GraphNode(Of TGraphNode))
Inherits GraphNode(Of StronglyConnectedComponent(Of TGraphNode))
Public ReadOnly ChildNodes As ArrayBuilder(Of TGraphNode)
Public Sub New(graph As Graph(Of StronglyConnectedComponent(Of TGraphNode)))
MyBase.New(graph)
ChildNodes = New ArrayBuilder(Of TGraphNode)()
End Sub
End Class
Private Class Graph(Of TGraphNode As GraphNode(Of TGraphNode))
Public ReadOnly Vertices As ArrayBuilder(Of TGraphNode)
Public Sub New()
Vertices = New ArrayBuilder(Of TGraphNode)()
End Sub
Public Sub AddEdge(
source As TGraphNode,
target As TGraphNode
)
AddNode(source)
AddNode(target)
source.OutgoingEdges.Add(target)
target.IncomingEdges.Add(source)
End Sub
Public Sub AddNode(
node As TGraphNode
)
Debug.Assert(node.Graph Is Me)
If Not node.IsAddedToVertices Then
Vertices.Add(node)
node.IsAddedToVertices = True
End If
End Sub
Public Sub RemoveEdge(
source As TGraphNode,
target As TGraphNode
)
Debug.Assert(Contains(source))
Debug.Assert(Contains(target))
Remove(source.OutgoingEdges, target)
Remove(target.IncomingEdges, source)
End Sub
Private Shared Sub Remove(list As ArrayBuilder(Of TGraphNode), toRemove As TGraphNode)
Dim lastIndex As Integer = list.Count - 1
For i As Integer = 0 To lastIndex Step 1
If list(i) Is toRemove Then
If i < lastIndex Then
list(i) = list(lastIndex)
End If
list.Clip(lastIndex)
Return
End If
Next
Throw ExceptionUtilities.Unreachable
End Sub
Public Function BuildStronglyConnectedComponents() As Graph(Of StronglyConnectedComponent(Of TGraphNode))
Dim sccGraph As New Graph(Of StronglyConnectedComponent(Of TGraphNode))()
' The first three steps are implementing Kosaraju's algorithm of finding
' the strongly connected components of a directed graph.
' Step 1: Perform regular Dfs and build a list with the deepest node last.
Dim orderedList = ArrayBuilder(Of TGraphNode).GetInstance()
Dfs(orderedList)
' Step 2: Reset graph algorithm Data
For Each current As TGraphNode In orderedList
current.AlgorithmData = New GraphAlgorithmData(Of TGraphNode)()
Next
' Step 3: Walk the nodes and place each tree in the forest in a separate node.
For Each current As TGraphNode In orderedList
If current.AlgorithmData.Color = DFSColor.None Then
Dim sccNode As New StronglyConnectedComponent(Of TGraphNode)(sccGraph)
CollectSccChildren(current, sccNode)
sccGraph.AddNode(sccNode)
End If
Next
orderedList.Free()
orderedList = Nothing
' Step 4: Link incoming and outgoing edges.
For Each sccNode As StronglyConnectedComponent(Of TGraphNode) In sccGraph.Vertices
For Each innerNodeIterCurrent As TGraphNode In sccNode.ChildNodes
For Each innerOutGoingInterCurrent As TGraphNode In innerNodeIterCurrent.OutgoingEdges
Dim target As StronglyConnectedComponent(Of TGraphNode) = innerOutGoingInterCurrent.AlgorithmData.StronglyConnectedComponent
' Don't create self-edges.
If sccNode IsNot target Then
sccGraph.AddEdge(sccNode, target)
End If
Next
Next
Next
Return sccGraph
End Function
Private Sub CollectSccChildren(
node As TGraphNode,
sccNode As StronglyConnectedComponent(Of TGraphNode)
)
node.AlgorithmData.Color = DFSColor.Grey
For Each current As TGraphNode In node.IncomingEdges
If current.AlgorithmData.Color = DFSColor.None Then
CollectSccChildren(current, sccNode)
End If
Next
node.AlgorithmData.Color = DFSColor.Black
Debug.Assert(node.AlgorithmData.StronglyConnectedComponent Is Nothing)
sccNode.ChildNodes.Add(node)
node.AlgorithmData.StronglyConnectedComponent = sccNode
End Sub
Public Sub TopoSort(resultList As ArrayBuilder(Of TGraphNode))
Dfs(resultList)
End Sub
Private Sub Dfs(resultList As ArrayBuilder(Of TGraphNode))
For Each current In Vertices
current.AlgorithmData = New GraphAlgorithmData(Of TGraphNode)()
Next
Dim oldListSize = resultList.Count
resultList.AddMany(Nothing, Vertices.Count)
Dim newListSize = resultList.Count
Dim insertAt As Integer = newListSize - 1
For Each current As TGraphNode In Vertices
If current.AlgorithmData.Color = DFSColor.None Then
DfsVisit(current, resultList, insertAt)
End If
Next
Debug.Assert(insertAt = oldListSize - 1)
End Sub
Private Sub DfsVisit(
node As TGraphNode,
resultList As ArrayBuilder(Of TGraphNode),
ByRef insertAt As Integer
)
node.AlgorithmData.Color = DFSColor.Grey
For Each current As TGraphNode In node.OutgoingEdges
If current.AlgorithmData.Color = DFSColor.None Then
DfsVisit(current, resultList, insertAt)
End If
Next
node.AlgorithmData.Color = DFSColor.Black
resultList(insertAt) = node
insertAt -= 1
End Sub
Private Function Contains(node As TGraphNode) As Boolean
Return node.Graph Is Me AndAlso node.IsAddedToVertices
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Emit/CodeGen/CodeGenWithEvents.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
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenWithEvents
Inherits BasicTestBase
<Fact>
Public Sub SimpleWithEventsTest()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Dim WithEvents X As Object = "AA", y As New Object
Sub Main(args As String())
Console.WriteLine(X)
X() = 42
Console.WriteLine(X())
_Y = 123
Console.WriteLine(_Y)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
AA
42
123
]]>).VerifyIL("Program.Main", <![CDATA[
{
// Code size 70 (0x46)
.maxstack 1
IL_0000: call "Function Program.get_X() As Object"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: call "Sub System.Console.WriteLine(Object)"
IL_000f: ldc.i4.s 42
IL_0011: box "Integer"
IL_0016: call "Sub Program.set_X(Object)"
IL_001b: call "Function Program.get_X() As Object"
IL_0020: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0025: call "Sub System.Console.WriteLine(Object)"
IL_002a: ldc.i4.s 123
IL_002c: box "Integer"
IL_0031: stsfld "Program._y As Object"
IL_0036: ldsfld "Program._y As Object"
IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0040: call "Sub System.Console.WriteLine(Object)"
IL_0045: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub StaticHandlesMe()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Program
Shared Event E1()
Shared Sub Main(args As String())
RaiseEvent E1()
End Sub
Shared Sub goo() Handles MyClass.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..cctor", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldnull
IL_0001: ldftn "Sub Program.goo()"
IL_0007: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0011: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub StaticHandlesMeInBase()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
class Base
Shared Event E1()
shared sub raiser()
RaiseEvent E1()
end sub
end class
Class Program
Inherits Base
Shared Sub Main(args As String())
raiser
End Sub
Shared Sub goo() Handles MyClass.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..cctor", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldnull
IL_0001: ldftn "Sub Program.goo()"
IL_0007: newobj "Sub Base.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: call "Sub Base.add_E1(Base.E1EventHandler)"
IL_0011: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMe()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class Program
Event E1()
Shared Sub Main(args As String())
Call (New Program).Raiser()
End Sub
Sub Raiser()
RaiseEvent E1()
End Sub
Shared Sub goo() Handles MyClass.e1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldnull
IL_0008: ldftn "Sub Program.goo()"
IL_000e: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0013: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0018: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMeNeedCtor()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class Program
Event E1(x As Integer)
Sub New()
Me.New(42)
End Sub
Sub New(x As Integer)
End Sub
Sub New(x As Long)
End Sub
Shared Sub Main(args As String())
Call (New Program()).Raiser()
End Sub
Sub Raiser()
RaiseEvent E1(123)
End Sub
Shared Sub goo() Handles MyClass.e1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: call "Sub Program..ctor(Integer)"
IL_0008: ret
}
]]>).VerifyIL("Program..ctor(Integer)", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler"
IL_000c: brfalse.s IL_0015
IL_000e: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler"
IL_0013: br.s IL_002b
IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__"
IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R6-1(Integer)"
IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0025: dup
IL_0026: stsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler"
IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0030: ret
}
]]>).VerifyIL("Program..ctor(Long)", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler"
IL_000c: brfalse.s IL_0015
IL_000e: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler"
IL_0013: br.s IL_002b
IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__"
IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R7-2(Integer)"
IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0025: dup
IL_0026: stsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler"
IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0030: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMeMismatched()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Option strict off
Imports System
Class base
Event E2(ByRef x As Integer)
Sub Raiser()
RaiseEvent E2(123)
End Sub
End Class
Class Program
Inherits base
Shared Event E1(x As Integer)
Shared Sub Main(args As String())
Call (New Program).Raiser()
End Sub
Shadows Sub Raiser()
RaiseEvent E1(123)
MyBase.Raiser()
End Sub
Sub goo1() Handles MyClass.E1
Console.WriteLine("handled1")
End Sub
Shared Sub goo2() Handles MyClass.E2
Console.WriteLine("handled2")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled1
handled2
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 66 (0x42)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub base..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Program._Lambda$__R0-1(Integer)"
IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0017: ldarg.0
IL_0018: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler"
IL_001d: brfalse.s IL_0026
IL_001f: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler"
IL_0024: br.s IL_003c
IL_0026: ldsfld "Program._Closure$__.$I As Program._Closure$__"
IL_002b: ldftn "Sub Program._Closure$__._Lambda$__R0-2(ByRef Integer)"
IL_0031: newobj "Sub base.E2EventHandler..ctor(Object, System.IntPtr)"
IL_0036: dup
IL_0037: stsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler"
IL_003c: call "Sub base.add_E2(base.E2EventHandler)"
IL_0041: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMeMismatchedStrict()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class base
Event E2(ByRef x As Integer)
Sub Raiser()
RaiseEvent E2(123)
End Sub
End Class
Class Program
Inherits base
Shared Event E1(x As Integer)
Shared Sub Main(args As String())
Call (New Program).Raiser()
End Sub
Shadows Sub Raiser()
RaiseEvent E1(123)
MyBase.Raiser()
End Sub
Sub goo1() Handles MyClass.E1
Console.WriteLine("handled1")
End Sub
Shared Function goo2(arg As Long) As Integer Handles MyClass.E1
Console.WriteLine("handled2")
Return 123
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled2
handled1
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub base..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Program._Lambda$__R1-2(Integer)"
IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0017: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub SimpleSharedWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1()
Sub raiser()
RaiseEvent E1()
End Sub
End Class
Class cls2
Shared WithEvents w As cls1
Public Shared Sub Main()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Private Shared Sub handler() Handles w.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1 V_1)
IL_0000: ldnull
IL_0001: ldftn "Sub cls2.handler()"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldsfld "cls2._w As cls1"
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.1
IL_0017: ldloc.0
IL_0018: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_001d: ldarg.0
IL_001e: stsfld "cls2._w As cls1"
IL_0023: ldsfld "cls2._w As cls1"
IL_0028: stloc.1
IL_0029: ldloc.1
IL_002a: brfalse.s IL_0033
IL_002c: ldloc.1
IL_002d: ldloc.0
IL_002e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0033: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub SimpleInstanceWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class cls1
Event E1()
Sub raiser()
RaiseEvent E1()
End Sub
End Class
Class cls2
WithEvents w As cls1
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Private Sub handler() Handles w.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1 V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub cls2.handler()"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "cls2._w As cls1"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: brfalse.s IL_001e
IL_0017: ldloc.1
IL_0018: ldloc.0
IL_0019: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_001e: ldarg.0
IL_001f: ldarg.1
IL_0020: stfld "cls2._w As cls1"
IL_0025: ldarg.0
IL_0026: ldfld "cls2._w As cls1"
IL_002b: stloc.1
IL_002c: ldloc.1
IL_002d: brfalse.s IL_0036
IL_002f: ldloc.1
IL_0030: ldloc.0
IL_0031: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0036: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub BaseInstanceWithEventsMultiple()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1(x As Integer)
Sub raiser()
RaiseEvent E1(123)
End Sub
End Class
Class base
Protected WithEvents w As cls1
End Class
Class cls2
Inherits base
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Private Sub handler() Handles w.E1, w.E1
Console.WriteLine("handled")
End Sub
Private shared Sub handlerS() Handles w.E1, w.E1
Console.WriteLine("handledS")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
handledS
handledS
handled
handled
handledS
handledS
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 196 (0xc4)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1.E1EventHandler V_1,
cls1.E1EventHandler V_2,
cls1.E1EventHandler V_3,
cls1 V_4)
IL_0000: ldarg.0
IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)"
IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler"
IL_001f: brfalse.s IL_0028
IL_0021: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler"
IL_0026: br.s IL_003e
IL_0028: ldsfld "cls2._Closure$__.$I As cls2._Closure$__"
IL_002d: ldftn "Sub cls2._Closure$__._Lambda$__R0-3(Integer)"
IL_0033: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0038: dup
IL_0039: stsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler"
IL_003e: stloc.2
IL_003f: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler"
IL_0044: brfalse.s IL_004d
IL_0046: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler"
IL_004b: br.s IL_0063
IL_004d: ldsfld "cls2._Closure$__.$I As cls2._Closure$__"
IL_0052: ldftn "Sub cls2._Closure$__._Lambda$__R0-4(Integer)"
IL_0058: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_005d: dup
IL_005e: stsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler"
IL_0063: stloc.3
IL_0064: ldarg.0
IL_0065: call "Function base.get_w() As cls1"
IL_006a: stloc.s V_4
IL_006c: ldloc.s V_4
IL_006e: brfalse.s IL_0090
IL_0070: ldloc.s V_4
IL_0072: ldloc.0
IL_0073: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0078: ldloc.s V_4
IL_007a: ldloc.1
IL_007b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0080: ldloc.s V_4
IL_0082: ldloc.2
IL_0083: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0088: ldloc.s V_4
IL_008a: ldloc.3
IL_008b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0090: ldarg.0
IL_0091: ldarg.1
IL_0092: call "Sub base.set_w(cls1)"
IL_0097: ldarg.0
IL_0098: call "Function base.get_w() As cls1"
IL_009d: stloc.s V_4
IL_009f: ldloc.s V_4
IL_00a1: brfalse.s IL_00c3
IL_00a3: ldloc.s V_4
IL_00a5: ldloc.0
IL_00a6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00ab: ldloc.s V_4
IL_00ad: ldloc.1
IL_00ae: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00b3: ldloc.s V_4
IL_00b5: ldloc.2
IL_00b6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00bb: ldloc.s V_4
IL_00bd: ldloc.3
IL_00be: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00c3: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub PartialHandles()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1(x As Integer)
Sub raiser()
RaiseEvent E1(123)
End Sub
End Class
Class base
Public WithEvents w As cls1
End Class
Class cls2
Inherits base
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Private Sub handlerConcrete() Handles w.E1, w.E1
Console.WriteLine("handled")
End Sub
Partial Private Sub handlerConcrete() Handles w.E1, w.E1
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
handled
handled
handled
handled
handled
handled
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 148 (0x94)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1.E1EventHandler V_1,
cls1.E1EventHandler V_2,
cls1.E1EventHandler V_3,
cls1 V_4)
IL_0000: ldarg.0
IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)"
IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldarg.0
IL_001b: ldftn "Sub cls2._Lambda$__R0-3(Integer)"
IL_0021: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldftn "Sub cls2._Lambda$__R0-4(Integer)"
IL_002e: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0033: stloc.3
IL_0034: ldarg.0
IL_0035: call "Function base.get_w() As cls1"
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: brfalse.s IL_0060
IL_0040: ldloc.s V_4
IL_0042: ldloc.0
IL_0043: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0048: ldloc.s V_4
IL_004a: ldloc.1
IL_004b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0050: ldloc.s V_4
IL_0052: ldloc.2
IL_0053: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0058: ldloc.s V_4
IL_005a: ldloc.3
IL_005b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0060: ldarg.0
IL_0061: ldarg.1
IL_0062: call "Sub base.set_w(cls1)"
IL_0067: ldarg.0
IL_0068: call "Function base.get_w() As cls1"
IL_006d: stloc.s V_4
IL_006f: ldloc.s V_4
IL_0071: brfalse.s IL_0093
IL_0073: ldloc.s V_4
IL_0075: ldloc.0
IL_0076: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_007b: ldloc.s V_4
IL_007d: ldloc.1
IL_007e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0083: ldloc.s V_4
IL_0085: ldloc.2
IL_0086: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_008b: ldloc.s V_4
IL_008d: ldloc.3
IL_008e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0093: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub PartialHandles1()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1(x As Integer)
Sub raiser()
RaiseEvent E1(123)
End Sub
End Class
Class base
Event E2(x As Integer)
Public WithEvents w As cls1
End Class
Class cls2
Inherits base
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Partial Private Sub handlerPartial(x as integer) Handles w.E1
End Sub
Partial Private Sub handlerPartial() Handles w.E1
End Sub
Partial Private Sub handlerPartial1(x as integer) Handles me.E2
End Sub
Partial Private Sub handlerPartial2() Handles me.E2
End Sub
End Class
</file>
</compilation>, expectedOutput:="")
End Sub
<Fact>
Public Sub ProtectedWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class c1
Protected Event e()
Sub raiser()
RaiseEvent e()
End Sub
End Class
Class c2
Inherits c1
End Class
Class c3
Inherits c2
Sub goo() Handles MyBase.e
gstrexpectedresult = "working!!"
End Sub
End Class
Module m1
Public gstrexpectedresult As String
Sub main()
Dim o As New c3
o.raiser()
Console.WriteLine(gstrexpectedresult)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[working!!
]]>).Compilation
End Sub
<Fact>
Public Sub GenericWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module m1
Public gresult As String = ""
Sub main()
Dim t As New C1(Of TClass)
t.o = New TClass
t.o.raiser()
Console.WriteLine(gresult)
End Sub
End Module
Class C1(Of T As {iTest, Class})
Public WithEvents o As T
Sub EventHandler2() Handles o.Event2
gresult = gresult & "inside EventHandler2"
End Sub
Sub EventHandler1()
gresult = gresult & "inside EH1"
End Sub
Sub adder()
AddHandler o.Event2, AddressOf EventHandler1
End Sub
End Class
Class TClass
Implements iTest
Public Event Event21() Implements iTest.Event2
Sub raiser()
RaiseEvent Event21()
End Sub
End Class
Public Interface iTest
Event Event2()
End Interface
</file>
</compilation>, expectedOutput:=<![CDATA[inside EventHandler2
]]>).VerifyIL("C1(Of T).set_o(T)", <![CDATA[
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (iTest.Event2EventHandler V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub C1(Of T).EventHandler2()"
IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "C1(Of T)._o As T"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: box "T"
IL_001a: brfalse.s IL_002a
IL_001c: ldloca.s V_1
IL_001e: ldloc.0
IL_001f: constrained. "T"
IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)"
IL_002a: ldarg.0
IL_002b: ldarg.1
IL_002c: stfld "C1(Of T)._o As T"
IL_0031: ldarg.0
IL_0032: ldfld "C1(Of T)._o As T"
IL_0037: stloc.1
IL_0038: ldloc.1
IL_0039: box "T"
IL_003e: brfalse.s IL_004e
IL_0040: ldloca.s V_1
IL_0042: ldloc.0
IL_0043: constrained. "T"
IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)"
IL_004e: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub GenericWithEventsNoOpt()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module m1
Public gresult As String = ""
Sub main()
Dim t As New C1(Of TClass)
t.o = New TClass
t.o.raiser()
Console.WriteLine(gresult)
End Sub
End Module
Class C1(Of T As {iTest, Class})
Public WithEvents o As T
Sub EventHandler2() Handles o.Event2
gresult = gresult & "inside EventHandler2"
End Sub
Sub EventHandler1()
gresult = gresult & "inside EH1"
End Sub
Sub adder()
AddHandler o.Event2, AddressOf EventHandler1
End Sub
End Class
Class TClass
Implements iTest
Public Event Event21() Implements iTest.Event2
Sub raiser()
RaiseEvent Event21()
End Sub
End Class
Public Interface iTest
Event Event2()
End Interface
</file>
</compilation>, expectedOutput:="inside EventHandler2")
c.VerifyIL("C1(Of T).set_o(T)", <![CDATA[
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (iTest.Event2EventHandler V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub C1(Of T).EventHandler2()"
IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "C1(Of T)._o As T"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: box "T"
IL_001a: brfalse.s IL_002a
IL_001c: ldloca.s V_1
IL_001e: ldloc.0
IL_001f: constrained. "T"
IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)"
IL_002a: ldarg.0
IL_002b: ldarg.1
IL_002c: stfld "C1(Of T)._o As T"
IL_0031: ldarg.0
IL_0032: ldfld "C1(Of T)._o As T"
IL_0037: stloc.1
IL_0038: ldloc.1
IL_0039: box "T"
IL_003e: brfalse.s IL_004e
IL_0040: ldloca.s V_1
IL_0042: ldloc.0
IL_0043: constrained. "T"
IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)"
IL_004e: ret
}
]]>)
End Sub
<WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")>
<WorkItem(545182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545182")>
<WorkItem(545184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545184")>
<Fact>
Public Sub TestHandlesForWithEventsFromBaseFromADifferentAssembly()
Dim assembly1Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly1",
<![CDATA[Public Class c1
Sub New()
goo = Me
End Sub
Public Event loo()
Public WithEvents goo As c1
Sub raise()
RaiseEvent loo()
End Sub
End Class]]>,
compilationOptions:=TestOptions.ReleaseDll)
' Verify that "AccessedThroughPropertyAttribute" is being emitted for WithEvents field.
Dim assembly1Verifier = CompileAndVerify(assembly1Compilation, expectedSignatures:=
{
Signature("c1", "_goo", ".field [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] " &
"[System.Runtime.CompilerServices.AccessedThroughPropertyAttribute(""goo"")] private instance c1 _goo")
})
assembly1Verifier.VerifyDiagnostics()
Dim assembly2Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly2",
<![CDATA[Imports System
Class c2
Inherits c1
Public res As Boolean = False
Sub test() Handles goo.loo 'here
res = True
End Sub
End Class
Public Module Program
Sub Main()
Dim c As New c2
c.goo.raise()
Console.WriteLine(c.res)
End Sub
End Module]]>,
compilationOptions:=TestOptions.ReleaseExe,
referencedCompilations:={assembly1Compilation})
CompileAndVerify(assembly2Compilation, <![CDATA[True]]>).VerifyDiagnostics()
End Sub
<WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")>
<WorkItem(545185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545185")>
<Fact>
Public Sub TestNameOfWithEventsSetterParameter()
Dim comp = CreateVisualBasicCompilation("TestNameOfWithEventsSetterParameter",
<![CDATA[Public Class c1
Sub New()
goo = Me
End Sub
Public WithEvents goo As c1
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim verifier = CompileAndVerify(comp, expectedSignatures:=
{
Signature("c1", "goo", ".property readwrite instance c1 goo"),
Signature("c1", "set_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance System.Void set_goo(c1 WithEventsValue) cil managed synchronized"),
Signature("c1", "get_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance c1 get_goo() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(529548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529548")>
<Fact()>
Public Sub TestIssueWeFixedInNativeCompiler()
Dim comp = CreateVisualBasicCompilation("TestIssueWeFixedInNativeCompiler",
<![CDATA[
Imports System
Interface I1(Of U)
Event E1(ByVal a As U)
End Interface
Class C1(Of T As {Exception, I1(Of T)})
Dim WithEvents x As T
'Native compiler used to report an incorrect error on the below line - "Method 'Public Sub goo(a As T)' cannot handle event 'Public Event E1(a As U)' because they do not have a compatible signature".
'This was a bug in the native compiler (see Bug: VSWhidbey/544224) that got fixed in Roslyn.
'See Vladimir's comments in bug 13489 for more details.
Sub goo(ByVal a As T) Handles x.E1
End Sub
Sub bar()
AddHandler x.E1, AddressOf goo 'AddHandler should also work
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim verifier = CompileAndVerify(comp)
verifier.VerifyDiagnostics()
End Sub
<WorkItem(545188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545188")>
<Fact>
Public Sub Bug13470()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Program
Shared Sub Main()
Dim c1 = GetType(C1)
Dim _Goo = c1.GetField("_Goo", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance)
Dim obsolete = _Goo.GetCustomAttributes(GetType(ObsoleteAttribute), False)
System.Console.WriteLine(obsolete.Length = 1)
End Sub
End Class
Class C1
<Obsolete> WithEvents Goo as C1
End Class
]]></file>
</compilation>, expectedOutput:="True")
End Sub
<WorkItem(545187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545187")>
<Fact>
Public Sub Bug13469()
'Note: Below IL is for the following VB code compiled with Dev11 (using /debug-) -
'Public Class c1
' Sub New()
' goo = Me
' End Sub
' Public Event loo()
' Public WithEvents goo As C1
' Sub raise()
' RaiseEvent loo()
' End Sub
'End Class
Dim customIL = <![CDATA[
.class public auto ansi c1
extends [mscorlib]System.Object
{
.class auto ansi sealed nested public looEventHandler
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname
instance void .ctor(object TargetObject,
native int TargetMethod) runtime managed
{
} // end of method looEventHandler::.ctor
.method public newslot strict virtual
instance class [mscorlib]System.IAsyncResult
BeginInvoke(class [mscorlib]System.AsyncCallback DelegateCallback,
object DelegateAsyncState) runtime managed
{
} // end of method looEventHandler::BeginInvoke
.method public newslot strict virtual
instance void EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed
{
} // end of method looEventHandler::EndInvoke
.method public newslot strict virtual
instance void Invoke() runtime managed
{
} // end of method looEventHandler::Invoke
} // end of class looEventHandler
.field private class c1/looEventHandler looEvent
.field private class c1 _goo
.custom instance void [mscorlib]System.Runtime.CompilerServices.AccessedThroughPropertyAttribute::.ctor(string) = ( 01 00 03 67 6F 6F 00 00 ) // ...goo..
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ldarg.0
IL_0007: ldarg.0
IL_0008: callvirt instance void c1::set_goo(class c1)
IL_000d: ret
} // end of method c1::.ctor
.method public specialname instance void
add_loo(class c1/looEventHandler obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class c1/looEventHandler c1::looEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass c1/looEventHandler
IL_0012: stfld class c1/looEventHandler c1::looEvent
IL_0017: ret
} // end of method c1::add_loo
.method public specialname instance void
remove_loo(class c1/looEventHandler obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class c1/looEventHandler c1::looEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass c1/looEventHandler
IL_0012: stfld class c1/looEventHandler c1::looEvent
IL_0017: ret
} // end of method c1::remove_loo
.method public newslot specialname strict virtual
instance class c1 get_goo() cil managed
{
// Code size 11 (0xb)
.maxstack 1
.locals init (class c1 V_0)
IL_0000: ldarg.0
IL_0001: ldfld class c1 c1::_goo
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
} // end of method c1::get_goo
.method public newslot specialname strict virtual
instance void set_goo(class c1 WithEventsValue) cil managed synchronized
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld class c1 c1::_goo
IL_0007: ret
} // end of method c1::set_goo
.method public instance void raise() cil managed
{
// Code size 17 (0x11)
.maxstack 1
.locals init (class c1/looEventHandler V_0)
IL_0000: ldarg.0
IL_0001: ldfld class c1/looEventHandler c1::looEvent
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: callvirt instance void c1/looEventHandler::Invoke()
IL_0010: ret
} // end of method c1::raise
.event c1/looEventHandler loo
{
.addon instance void c1::add_loo(class c1/looEventHandler)
.removeon instance void c1::remove_loo(class c1/looEventHandler)
} // end of event c1::loo
.property instance class c1 goo()
{
.get instance class c1 c1::get_goo()
.set instance void c1::set_goo(class c1)
} // end of property c1::goo
} // end of class c1
]]>
Dim compilation = CreateCompilationWithCustomILSource(
<compilation>
<file name="a.vb">
Imports System
Class c2
Inherits c1
Public res As Boolean = False
Sub test() Handles goo.loo 'here
res = True
End Sub
End Class
Public Module Program
Sub Main()
Dim c As New c2
c.goo.raise()
Console.WriteLine(c.res)
End Sub
End Module
</file>
</compilation>, customIL.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics()
End Sub
<Fact>
Public Sub SynthesizedOverridingWithEventsProperty()
Dim source =
<compilation>
<file>
Public Class Base
Protected Friend WithEvents w As Base = Me
Public Event e As System.Action
Sub H1() Handles w.e
End Sub
End Class
Public Class Derived
Inherits Base
Sub H2() Handles w.e
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250")>
Public Sub HookupOrder()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Class Base
Protected Friend WithEvents w As Base = Me
Public Event e As Action(Of Integer)
Sub BaseH1() Handles w.e
Console.WriteLine(" BaseH1")
End Sub
Function BaseH2(ParamArray x() As Integer) Handles Me.e
Console.WriteLine(" BaseH2")
Return 0
End Function
Sub Raise()
RaiseEvent e(1)
End Sub
End Class
Public Class Derived
Inherits Base
Function DerivedH2(ParamArray x() As Integer) Handles Me.e
Console.WriteLine(" DerivedH2")
Return 0
End Function
Sub DerivedH1() Handles w.e
Console.WriteLine(" DerivedH1")
End Sub
End Class
Public Module Program
Sub Main()
Console.WriteLine("Base")
Dim x = New Base()
x.Raise()
Console.WriteLine("Derived")
x = New Derived
x.Raise()
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[Base
BaseH2
BaseH1
Derived
BaseH2
BaseH1
DerivedH1
DerivedH2
]]>)
End Sub
<Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")>
Public Sub TestExecutionOrder1()
Dim vbCompilation = CreateVisualBasicCompilation("TestExecutionOrder1",
<) Handles w.e, Me.e, MyClass.e
Console.WriteLine("7")
Return 1.0
End Function
Sub Raise3()
RaiseEvent e(Nothing)
End Sub
End Class
Public Module Program
Sub Main()
Dim x = New Derived(Of Base(Of ArgumentException, String, S, ArgumentException,
Dictionary(Of String, S), List(Of IList(Of ArgumentException))))
x.Raise()
x.Raise2()
x.w.Raise()
x.w2.Raise()
x.w2.Raise2()
x.Raise3()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
'Breaking Change: Dev11 processes event handlers in a different order than Roslyn.
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[2
4
3
5
7
2
6
5
5
7
7]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")>
Public Sub TestExecutionOrder2()
Dim assembly1Compilation = CreateVisualBasicCompilation("TestExecutionOrder2",
<![CDATA[Option Strict Off
Imports System, System.Runtime.CompilerServices
Imports AliasedType = Base
<Assembly: InternalsVisibleTo("Assembly2")>
Public Class Base
Protected WithEvents w As AliasedType = Me, x As Base = Me, y As Base = Me, z As New System.Collections.Generic.List(Of String) From {"123"}
Protected Friend Event e As Action(Of Integer)
Friend Sub H1() Handles w.e, x.e
Console.WriteLine("Base H1")
End Sub
Public Function H2(ParamArray x() As Integer) Handles x.e, w.e, Me.e, MyClass.e
Console.WriteLine("Base H2")
Return 0
End Function
Overridable Sub Raise()
RaiseEvent e(1)
End Sub
End Class
Public Class Base2 : Inherits Base
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim assembly1Verifier = CompileAndVerify(assembly1Compilation)
assembly1Verifier.VerifyDiagnostics()
Dim assembly2Compilation = CreateVisualBasicCompilation("Assembly2",
<![CDATA[Imports System
Public Class Derived : Inherits Base2
Shadows Event e As Action(Of Exception)
Private Shadows Sub H1() Handles y.e, MyBase.e, x.e, w.e
Console.WriteLine("Derived H1")
End Sub
Protected Shadows Function H2(ParamArray x() As Integer) Handles MyBase.e
Console.WriteLine("Derived H2")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Console.WriteLine("Base")
Dim x = New Base()
x.Raise()
Console.WriteLine("Derived")
x = New Derived
x.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={assembly1Compilation})
'Breaking Change: Dev11 processes event handlers in a different order than Roslyn.
Dim assembly2Verifier = CompileAndVerify(assembly2Compilation,
expectedOutput:=<![CDATA[Base
Base H2
Base H2
Base H1
Base H2
Base H1
Base H2
Derived
Base H2
Base H2
Base H1
Base H2
Derived H1
Base H1
Base H2
Derived H1
Derived H1
Derived H1
Derived H2]]>)
assembly2Verifier.VerifyDiagnostics()
End Sub
<Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250"), WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")>
Public Sub TestCrossLanguageOptionalAndParamarray1()
Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray1_CS",
<![CDATA[public class CSClass
{
public delegate int bar(string x = "");
public event bar ev;
public void raise()
{
ev("BASE");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray1_VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo(x As String) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED1")
Return 0
End Function
Function Goo(x As String, ParamArray y() As Integer) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED2")
Return 0
End Function
Function Goo2(Optional x As String = "") Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED3")
Return 0
End Function
Function Goo2(ParamArray x() As String) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED4")
Return 0
End Function
Function Goo2(x As String, Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED5")
Return 0
End Function
Function Goo3(Optional x As String = "", Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED6")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
'Breaking Change: Dev11 processes event handlers in a different order than Roslyn.
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[BASE
DERIVED1
BASE
DERIVED1
BASE
DERIVED2
BASE
DERIVED2
BASE
DERIVED3
BASE
DERIVED3
System.String[]
DERIVED4
System.String[]
DERIVED4
BASE
DERIVED5
BASE
DERIVED5
BASE
DERIVED6
BASE
DERIVED6
BASE
DERIVED1
BASE
DERIVED2
BASE
DERIVED3
System.String[]
DERIVED4
BASE
DERIVED5
BASE
DERIVED6]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestCrossLanguageOptionalAndPAramarray2()
Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndPAramarray2_CS",
<![CDATA[public class CSClass
{
public delegate int bar(params int[] y);
public event bar ev;
public void raise()
{
ev(1, 2, 3);
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndPAramarray2_VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo(x As Integer()) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED1")
Return 0
End Function
Function Goo2(ParamArray x As Integer()) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED2")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[System.Int32[]
DERIVED1
System.Int32[]
DERIVED1
System.Int32[]
DERIVED2
System.Int32[]
DERIVED2
System.Int32[]
DERIVED1
System.Int32[]
DERIVED2]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestCrossLanguageOptionalAndParamarray_Error1()
Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray_Error1_CS",
<![CDATA[public class CSClass
{
public delegate int bar(params int[] y);
public event bar ev;
public void raise()
{
ev(1, 2, 3);
}
}]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray_Error1_VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo2(x As Integer) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED1")
Return 0
End Function
Function Goo2(x As Integer, Optional y As Integer = 1) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED2")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"))
End Sub
<Fact, WorkItem(545257, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545257")>
Public Sub TestCrossLanguageOptionalAndParamarray_Error2()
Dim csCompilation = CreateCSharpCompilation("CS",
<![CDATA[public class CSClass
{
public delegate int bar(params int[] y);
public event bar ev;
public void raise()
{
ev(1, 2, 3);
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo(Optional x As Integer = 1) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("PASS")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"))
End Sub
<Fact>
Public Sub DelegateRelaxationStubsUniqueNaming1()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class WE
Event V As Action(Of Integer, Integer)
Event W As Action(Of Long, Long)
End Class
Class B
Public WithEvents A3 As WE
End Class
Class D
Inherits B
Public WithEvents A1 As WE
Public WithEvents A2 As WE
End Class
Class E
Inherits D
Sub G(z1 As Double, z2 As Double) Handles A1.V, A3.W
Console.WriteLine(z1 + z2)
End Sub
Sub G(z1 As Double, z2 As Integer) Handles A1.V, A3.W
Console.WriteLine(z1 + z2)
End Sub
Sub G(z1 As Integer, z2 As Double) Handles A2.V, A3.W, A1.V
Console.WriteLine(z1 + z2)
End Sub
Sub G(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V
Console.WriteLine(z1 + z2)
End Sub
Sub F(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V
Console.WriteLine(z1 + z2)
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact>
Public Sub DelegateRelaxationStubsUniqueNaming2()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class WE
Public Event V1 As Action(Of Integer)
Public Event V2 As Action(Of Integer)
End Class
Class B
Public WithEvents we As WE = New WE
Public Event W1 As Action(Of Integer)
Public Event W2 As Action(Of Integer)
End Class
Class C
Inherits B
Public Event U1 As Action(Of Integer)
Public Event U2 As Action(Of Integer)
Sub F() Handles we.V1, we.V2, MyBase.W1, MyBase.W2, Me.U1, Me.U2
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")>
Public Sub MultipleInitializationsWithAsNew_01()
Dim source =
<compilation>
<file name="a.vb">
Class C1
Shared WithEvents a1, b1, c1 As New C2()
WithEvents a2, b2, c2 As New C2()
Shared a3, b3, c3 As New C2()
Dim a4, b4, c4 As New C2()
Shared Sub Main()
Check(a1, b1, c1)
Check(a3, b3, c3)
Dim c as New C1()
Check(c.a2, c.b2, c.c2)
Check(c.a4, c.b4, c.c4)
End Sub
Private Shared Sub Check(a As Object, b As Object, c As Object)
System.Console.WriteLine(a Is Nothing)
System.Console.WriteLine(b Is Nothing)
System.Console.WriteLine(c Is Nothing)
System.Console.WriteLine(a Is b)
System.Console.WriteLine(a Is c)
System.Console.WriteLine(b Is c)
End Sub
End Class
Class C2
End Class
</file>
</compilation>
CompileAndVerify(source, expectedOutput:=
<![CDATA[
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
]]>)
End Sub
<Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")>
Public Sub MultipleInitializationsWithAsNew_02()
Dim source =
<compilation>
<file name="a.vb">
Class C1
Shared WithEvents a, b, c As New C1() With {.P1 = 2}
Shared Sub Main()
System.Console.WriteLine(a.P1)
System.Console.WriteLine(b.P1)
System.Console.WriteLine(c.P1)
System.Console.WriteLine(a Is b)
System.Console.WriteLine(a Is c)
System.Console.WriteLine(b Is c)
End Sub
Public P1 As Integer
End Class
</file>
</compilation>
CompileAndVerify(source, expectedOutput:=
<![CDATA[
2
2
2
False
False
False
]]>).
VerifyIL("C1..cctor",
<![CDATA[
{
// Code size 52 (0x34)
.maxstack 3
IL_0000: newobj "Sub C1..ctor()"
IL_0005: dup
IL_0006: ldc.i4.2
IL_0007: stfld "C1.P1 As Integer"
IL_000c: call "Sub C1.set_a(C1)"
IL_0011: newobj "Sub C1..ctor()"
IL_0016: dup
IL_0017: ldc.i4.2
IL_0018: stfld "C1.P1 As Integer"
IL_001d: call "Sub C1.set_b(C1)"
IL_0022: newobj "Sub C1..ctor()"
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: stfld "C1.P1 As Integer"
IL_002e: call "Sub C1.set_c(C1)"
IL_0033: ret
}
]]>)
End Sub
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class CodeGenWithEvents
Inherits BasicTestBase
<Fact>
Public Sub SimpleWithEventsTest()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Imports System.Collections.Generic
Imports System.Linq
Module Program
Dim WithEvents X As Object = "AA", y As New Object
Sub Main(args As String())
Console.WriteLine(X)
X() = 42
Console.WriteLine(X())
_Y = 123
Console.WriteLine(_Y)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[
AA
42
123
]]>).VerifyIL("Program.Main", <![CDATA[
{
// Code size 70 (0x46)
.maxstack 1
IL_0000: call "Function Program.get_X() As Object"
IL_0005: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_000a: call "Sub System.Console.WriteLine(Object)"
IL_000f: ldc.i4.s 42
IL_0011: box "Integer"
IL_0016: call "Sub Program.set_X(Object)"
IL_001b: call "Function Program.get_X() As Object"
IL_0020: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0025: call "Sub System.Console.WriteLine(Object)"
IL_002a: ldc.i4.s 123
IL_002c: box "Integer"
IL_0031: stsfld "Program._y As Object"
IL_0036: ldsfld "Program._y As Object"
IL_003b: call "Function System.Runtime.CompilerServices.RuntimeHelpers.GetObjectValue(Object) As Object"
IL_0040: call "Sub System.Console.WriteLine(Object)"
IL_0045: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub StaticHandlesMe()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class Program
Shared Event E1()
Shared Sub Main(args As String())
RaiseEvent E1()
End Sub
Shared Sub goo() Handles MyClass.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..cctor", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldnull
IL_0001: ldftn "Sub Program.goo()"
IL_0007: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0011: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub StaticHandlesMeInBase()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
class Base
Shared Event E1()
shared sub raiser()
RaiseEvent E1()
end sub
end class
Class Program
Inherits Base
Shared Sub Main(args As String())
raiser
End Sub
Shared Sub goo() Handles MyClass.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..cctor", <![CDATA[
{
// Code size 18 (0x12)
.maxstack 2
IL_0000: ldnull
IL_0001: ldftn "Sub Program.goo()"
IL_0007: newobj "Sub Base.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: call "Sub Base.add_E1(Base.E1EventHandler)"
IL_0011: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMe()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class Program
Event E1()
Shared Sub Main(args As String())
Call (New Program).Raiser()
End Sub
Sub Raiser()
RaiseEvent E1()
End Sub
Shared Sub goo() Handles MyClass.e1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 25 (0x19)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldnull
IL_0008: ldftn "Sub Program.goo()"
IL_000e: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0013: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0018: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMeNeedCtor()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class Program
Event E1(x As Integer)
Sub New()
Me.New(42)
End Sub
Sub New(x As Integer)
End Sub
Sub New(x As Long)
End Sub
Shared Sub Main(args As String())
Call (New Program()).Raiser()
End Sub
Sub Raiser()
RaiseEvent E1(123)
End Sub
Shared Sub goo() Handles MyClass.e1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 9 (0x9)
.maxstack 2
IL_0000: ldarg.0
IL_0001: ldc.i4.s 42
IL_0003: call "Sub Program..ctor(Integer)"
IL_0008: ret
}
]]>).VerifyIL("Program..ctor(Integer)", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler"
IL_000c: brfalse.s IL_0015
IL_000e: ldsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler"
IL_0013: br.s IL_002b
IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__"
IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R6-1(Integer)"
IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0025: dup
IL_0026: stsfld "Program._Closure$__.$IR6-1 As Program.E1EventHandler"
IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0030: ret
}
]]>).VerifyIL("Program..ctor(Long)", <![CDATA[
{
// Code size 49 (0x31)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub Object..ctor()"
IL_0006: ldarg.0
IL_0007: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler"
IL_000c: brfalse.s IL_0015
IL_000e: ldsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler"
IL_0013: br.s IL_002b
IL_0015: ldsfld "Program._Closure$__.$I As Program._Closure$__"
IL_001a: ldftn "Sub Program._Closure$__._Lambda$__R7-2(Integer)"
IL_0020: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0025: dup
IL_0026: stsfld "Program._Closure$__.$IR7-2 As Program.E1EventHandler"
IL_002b: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0030: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMeMismatched()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Option strict off
Imports System
Class base
Event E2(ByRef x As Integer)
Sub Raiser()
RaiseEvent E2(123)
End Sub
End Class
Class Program
Inherits base
Shared Event E1(x As Integer)
Shared Sub Main(args As String())
Call (New Program).Raiser()
End Sub
Shadows Sub Raiser()
RaiseEvent E1(123)
MyBase.Raiser()
End Sub
Sub goo1() Handles MyClass.E1
Console.WriteLine("handled1")
End Sub
Shared Sub goo2() Handles MyClass.E2
Console.WriteLine("handled2")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled1
handled2
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 66 (0x42)
.maxstack 3
IL_0000: ldarg.0
IL_0001: call "Sub base..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Program._Lambda$__R0-1(Integer)"
IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0017: ldarg.0
IL_0018: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler"
IL_001d: brfalse.s IL_0026
IL_001f: ldsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler"
IL_0024: br.s IL_003c
IL_0026: ldsfld "Program._Closure$__.$I As Program._Closure$__"
IL_002b: ldftn "Sub Program._Closure$__._Lambda$__R0-2(ByRef Integer)"
IL_0031: newobj "Sub base.E2EventHandler..ctor(Object, System.IntPtr)"
IL_0036: dup
IL_0037: stsfld "Program._Closure$__.$IR0-2 As base.E2EventHandler"
IL_003c: call "Sub base.add_E2(base.E2EventHandler)"
IL_0041: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub InstanceHandlesMeMismatchedStrict()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Option Strict On
Imports System
Class base
Event E2(ByRef x As Integer)
Sub Raiser()
RaiseEvent E2(123)
End Sub
End Class
Class Program
Inherits base
Shared Event E1(x As Integer)
Shared Sub Main(args As String())
Call (New Program).Raiser()
End Sub
Shadows Sub Raiser()
RaiseEvent E1(123)
MyBase.Raiser()
End Sub
Sub goo1() Handles MyClass.E1
Console.WriteLine("handled1")
End Sub
Shared Function goo2(arg As Long) As Integer Handles MyClass.E1
Console.WriteLine("handled2")
Return 123
End Function
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled2
handled1
]]>).VerifyIL("Program..ctor", <![CDATA[
{
// Code size 24 (0x18)
.maxstack 2
IL_0000: ldarg.0
IL_0001: call "Sub base..ctor()"
IL_0006: ldarg.0
IL_0007: ldftn "Sub Program._Lambda$__R1-2(Integer)"
IL_000d: newobj "Sub Program.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0012: call "Sub Program.add_E1(Program.E1EventHandler)"
IL_0017: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub SimpleSharedWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1()
Sub raiser()
RaiseEvent E1()
End Sub
End Class
Class cls2
Shared WithEvents w As cls1
Public Shared Sub Main()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Private Shared Sub handler() Handles w.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 52 (0x34)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1 V_1)
IL_0000: ldnull
IL_0001: ldftn "Sub cls2.handler()"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldsfld "cls2._w As cls1"
IL_0012: stloc.1
IL_0013: ldloc.1
IL_0014: brfalse.s IL_001d
IL_0016: ldloc.1
IL_0017: ldloc.0
IL_0018: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_001d: ldarg.0
IL_001e: stsfld "cls2._w As cls1"
IL_0023: ldsfld "cls2._w As cls1"
IL_0028: stloc.1
IL_0029: ldloc.1
IL_002a: brfalse.s IL_0033
IL_002c: ldloc.1
IL_002d: ldloc.0
IL_002e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0033: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub SimpleInstanceWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
imports system
Class cls1
Event E1()
Sub raiser()
RaiseEvent E1()
End Sub
End Class
Class cls2
WithEvents w As cls1
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Private Sub handler() Handles w.E1
Console.WriteLine("handled")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 55 (0x37)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1 V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub cls2.handler()"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "cls2._w As cls1"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: brfalse.s IL_001e
IL_0017: ldloc.1
IL_0018: ldloc.0
IL_0019: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_001e: ldarg.0
IL_001f: ldarg.1
IL_0020: stfld "cls2._w As cls1"
IL_0025: ldarg.0
IL_0026: ldfld "cls2._w As cls1"
IL_002b: stloc.1
IL_002c: ldloc.1
IL_002d: brfalse.s IL_0036
IL_002f: ldloc.1
IL_0030: ldloc.0
IL_0031: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0036: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub BaseInstanceWithEventsMultiple()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1(x As Integer)
Sub raiser()
RaiseEvent E1(123)
End Sub
End Class
Class base
Protected WithEvents w As cls1
End Class
Class cls2
Inherits base
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Private Sub handler() Handles w.E1, w.E1
Console.WriteLine("handled")
End Sub
Private shared Sub handlerS() Handles w.E1, w.E1
Console.WriteLine("handledS")
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
handledS
handledS
handled
handled
handledS
handledS
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 196 (0xc4)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1.E1EventHandler V_1,
cls1.E1EventHandler V_2,
cls1.E1EventHandler V_3,
cls1 V_4)
IL_0000: ldarg.0
IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)"
IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler"
IL_001f: brfalse.s IL_0028
IL_0021: ldsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler"
IL_0026: br.s IL_003e
IL_0028: ldsfld "cls2._Closure$__.$I As cls2._Closure$__"
IL_002d: ldftn "Sub cls2._Closure$__._Lambda$__R0-3(Integer)"
IL_0033: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0038: dup
IL_0039: stsfld "cls2._Closure$__.$IR0-3 As cls1.E1EventHandler"
IL_003e: stloc.2
IL_003f: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler"
IL_0044: brfalse.s IL_004d
IL_0046: ldsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler"
IL_004b: br.s IL_0063
IL_004d: ldsfld "cls2._Closure$__.$I As cls2._Closure$__"
IL_0052: ldftn "Sub cls2._Closure$__._Lambda$__R0-4(Integer)"
IL_0058: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_005d: dup
IL_005e: stsfld "cls2._Closure$__.$IR0-4 As cls1.E1EventHandler"
IL_0063: stloc.3
IL_0064: ldarg.0
IL_0065: call "Function base.get_w() As cls1"
IL_006a: stloc.s V_4
IL_006c: ldloc.s V_4
IL_006e: brfalse.s IL_0090
IL_0070: ldloc.s V_4
IL_0072: ldloc.0
IL_0073: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0078: ldloc.s V_4
IL_007a: ldloc.1
IL_007b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0080: ldloc.s V_4
IL_0082: ldloc.2
IL_0083: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0088: ldloc.s V_4
IL_008a: ldloc.3
IL_008b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0090: ldarg.0
IL_0091: ldarg.1
IL_0092: call "Sub base.set_w(cls1)"
IL_0097: ldarg.0
IL_0098: call "Function base.get_w() As cls1"
IL_009d: stloc.s V_4
IL_009f: ldloc.s V_4
IL_00a1: brfalse.s IL_00c3
IL_00a3: ldloc.s V_4
IL_00a5: ldloc.0
IL_00a6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00ab: ldloc.s V_4
IL_00ad: ldloc.1
IL_00ae: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00b3: ldloc.s V_4
IL_00b5: ldloc.2
IL_00b6: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00bb: ldloc.s V_4
IL_00bd: ldloc.3
IL_00be: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_00c3: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub PartialHandles()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1(x As Integer)
Sub raiser()
RaiseEvent E1(123)
End Sub
End Class
Class base
Public WithEvents w As cls1
End Class
Class cls2
Inherits base
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Private Sub handlerConcrete() Handles w.E1, w.E1
Console.WriteLine("handled")
End Sub
Partial Private Sub handlerConcrete() Handles w.E1, w.E1
End Sub
End Class
</file>
</compilation>, expectedOutput:=<![CDATA[handled
handled
handled
handled
handled
handled
handled
handled
]]>).VerifyIL("cls2.set_w", <![CDATA[
{
// Code size 148 (0x94)
.maxstack 2
.locals init (cls1.E1EventHandler V_0,
cls1.E1EventHandler V_1,
cls1.E1EventHandler V_2,
cls1.E1EventHandler V_3,
cls1 V_4)
IL_0000: ldarg.0
IL_0001: ldftn "Sub cls2._Lambda$__R0-1(Integer)"
IL_0007: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldftn "Sub cls2._Lambda$__R0-2(Integer)"
IL_0014: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0019: stloc.1
IL_001a: ldarg.0
IL_001b: ldftn "Sub cls2._Lambda$__R0-3(Integer)"
IL_0021: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0026: stloc.2
IL_0027: ldarg.0
IL_0028: ldftn "Sub cls2._Lambda$__R0-4(Integer)"
IL_002e: newobj "Sub cls1.E1EventHandler..ctor(Object, System.IntPtr)"
IL_0033: stloc.3
IL_0034: ldarg.0
IL_0035: call "Function base.get_w() As cls1"
IL_003a: stloc.s V_4
IL_003c: ldloc.s V_4
IL_003e: brfalse.s IL_0060
IL_0040: ldloc.s V_4
IL_0042: ldloc.0
IL_0043: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0048: ldloc.s V_4
IL_004a: ldloc.1
IL_004b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0050: ldloc.s V_4
IL_0052: ldloc.2
IL_0053: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0058: ldloc.s V_4
IL_005a: ldloc.3
IL_005b: callvirt "Sub cls1.remove_E1(cls1.E1EventHandler)"
IL_0060: ldarg.0
IL_0061: ldarg.1
IL_0062: call "Sub base.set_w(cls1)"
IL_0067: ldarg.0
IL_0068: call "Function base.get_w() As cls1"
IL_006d: stloc.s V_4
IL_006f: ldloc.s V_4
IL_0071: brfalse.s IL_0093
IL_0073: ldloc.s V_4
IL_0075: ldloc.0
IL_0076: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_007b: ldloc.s V_4
IL_007d: ldloc.1
IL_007e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0083: ldloc.s V_4
IL_0085: ldloc.2
IL_0086: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_008b: ldloc.s V_4
IL_008d: ldloc.3
IL_008e: callvirt "Sub cls1.add_E1(cls1.E1EventHandler)"
IL_0093: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub PartialHandles1()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class cls1
Event E1(x As Integer)
Sub raiser()
RaiseEvent E1(123)
End Sub
End Class
Class base
Event E2(x As Integer)
Public WithEvents w As cls1
End Class
Class cls2
Inherits base
Public Sub Test()
Dim o As New cls1
o.raiser()
w = o
o.raiser()
w = o
o.raiser()
w = Nothing
o.raiser()
End Sub
Public Shared Sub main()
Call (New cls2).Test()
End Sub
Partial Private Sub handlerPartial(x as integer) Handles w.E1
End Sub
Partial Private Sub handlerPartial() Handles w.E1
End Sub
Partial Private Sub handlerPartial1(x as integer) Handles me.E2
End Sub
Partial Private Sub handlerPartial2() Handles me.E2
End Sub
End Class
</file>
</compilation>, expectedOutput:="")
End Sub
<Fact>
Public Sub ProtectedWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Class c1
Protected Event e()
Sub raiser()
RaiseEvent e()
End Sub
End Class
Class c2
Inherits c1
End Class
Class c3
Inherits c2
Sub goo() Handles MyBase.e
gstrexpectedresult = "working!!"
End Sub
End Class
Module m1
Public gstrexpectedresult As String
Sub main()
Dim o As New c3
o.raiser()
Console.WriteLine(gstrexpectedresult)
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[working!!
]]>).Compilation
End Sub
<Fact>
Public Sub GenericWithEvents()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module m1
Public gresult As String = ""
Sub main()
Dim t As New C1(Of TClass)
t.o = New TClass
t.o.raiser()
Console.WriteLine(gresult)
End Sub
End Module
Class C1(Of T As {iTest, Class})
Public WithEvents o As T
Sub EventHandler2() Handles o.Event2
gresult = gresult & "inside EventHandler2"
End Sub
Sub EventHandler1()
gresult = gresult & "inside EH1"
End Sub
Sub adder()
AddHandler o.Event2, AddressOf EventHandler1
End Sub
End Class
Class TClass
Implements iTest
Public Event Event21() Implements iTest.Event2
Sub raiser()
RaiseEvent Event21()
End Sub
End Class
Public Interface iTest
Event Event2()
End Interface
</file>
</compilation>, expectedOutput:=<![CDATA[inside EventHandler2
]]>).VerifyIL("C1(Of T).set_o(T)", <![CDATA[
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (iTest.Event2EventHandler V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub C1(Of T).EventHandler2()"
IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "C1(Of T)._o As T"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: box "T"
IL_001a: brfalse.s IL_002a
IL_001c: ldloca.s V_1
IL_001e: ldloc.0
IL_001f: constrained. "T"
IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)"
IL_002a: ldarg.0
IL_002b: ldarg.1
IL_002c: stfld "C1(Of T)._o As T"
IL_0031: ldarg.0
IL_0032: ldfld "C1(Of T)._o As T"
IL_0037: stloc.1
IL_0038: ldloc.1
IL_0039: box "T"
IL_003e: brfalse.s IL_004e
IL_0040: ldloca.s V_1
IL_0042: ldloc.0
IL_0043: constrained. "T"
IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)"
IL_004e: ret
}
]]>).Compilation
End Sub
<Fact>
Public Sub GenericWithEventsNoOpt()
Dim c = CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Module m1
Public gresult As String = ""
Sub main()
Dim t As New C1(Of TClass)
t.o = New TClass
t.o.raiser()
Console.WriteLine(gresult)
End Sub
End Module
Class C1(Of T As {iTest, Class})
Public WithEvents o As T
Sub EventHandler2() Handles o.Event2
gresult = gresult & "inside EventHandler2"
End Sub
Sub EventHandler1()
gresult = gresult & "inside EH1"
End Sub
Sub adder()
AddHandler o.Event2, AddressOf EventHandler1
End Sub
End Class
Class TClass
Implements iTest
Public Event Event21() Implements iTest.Event2
Sub raiser()
RaiseEvent Event21()
End Sub
End Class
Public Interface iTest
Event Event2()
End Interface
</file>
</compilation>, expectedOutput:="inside EventHandler2")
c.VerifyIL("C1(Of T).set_o(T)", <![CDATA[
{
// Code size 79 (0x4f)
.maxstack 2
.locals init (iTest.Event2EventHandler V_0,
T V_1)
IL_0000: ldarg.0
IL_0001: ldftn "Sub C1(Of T).EventHandler2()"
IL_0007: newobj "Sub iTest.Event2EventHandler..ctor(Object, System.IntPtr)"
IL_000c: stloc.0
IL_000d: ldarg.0
IL_000e: ldfld "C1(Of T)._o As T"
IL_0013: stloc.1
IL_0014: ldloc.1
IL_0015: box "T"
IL_001a: brfalse.s IL_002a
IL_001c: ldloca.s V_1
IL_001e: ldloc.0
IL_001f: constrained. "T"
IL_0025: callvirt "Sub iTest.remove_Event2(iTest.Event2EventHandler)"
IL_002a: ldarg.0
IL_002b: ldarg.1
IL_002c: stfld "C1(Of T)._o As T"
IL_0031: ldarg.0
IL_0032: ldfld "C1(Of T)._o As T"
IL_0037: stloc.1
IL_0038: ldloc.1
IL_0039: box "T"
IL_003e: brfalse.s IL_004e
IL_0040: ldloca.s V_1
IL_0042: ldloc.0
IL_0043: constrained. "T"
IL_0049: callvirt "Sub iTest.add_Event2(iTest.Event2EventHandler)"
IL_004e: ret
}
]]>)
End Sub
<WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")>
<WorkItem(545182, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545182")>
<WorkItem(545184, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545184")>
<Fact>
Public Sub TestHandlesForWithEventsFromBaseFromADifferentAssembly()
Dim assembly1Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly1",
<![CDATA[Public Class c1
Sub New()
goo = Me
End Sub
Public Event loo()
Public WithEvents goo As c1
Sub raise()
RaiseEvent loo()
End Sub
End Class]]>,
compilationOptions:=TestOptions.ReleaseDll)
' Verify that "AccessedThroughPropertyAttribute" is being emitted for WithEvents field.
Dim assembly1Verifier = CompileAndVerify(assembly1Compilation, expectedSignatures:=
{
Signature("c1", "_goo", ".field [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] " &
"[System.Runtime.CompilerServices.AccessedThroughPropertyAttribute(""goo"")] private instance c1 _goo")
})
assembly1Verifier.VerifyDiagnostics()
Dim assembly2Compilation = CreateVisualBasicCompilation("TestHandlesForWithEventsFromBaseFromADifferentAssembly_Assembly2",
<![CDATA[Imports System
Class c2
Inherits c1
Public res As Boolean = False
Sub test() Handles goo.loo 'here
res = True
End Sub
End Class
Public Module Program
Sub Main()
Dim c As New c2
c.goo.raise()
Console.WriteLine(c.res)
End Sub
End Module]]>,
compilationOptions:=TestOptions.ReleaseExe,
referencedCompilations:={assembly1Compilation})
CompileAndVerify(assembly2Compilation, <![CDATA[True]]>).VerifyDiagnostics()
End Sub
<WorkItem(6214, "https://github.com/dotnet/roslyn/issues/6214")>
<WorkItem(545185, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545185")>
<Fact>
Public Sub TestNameOfWithEventsSetterParameter()
Dim comp = CreateVisualBasicCompilation("TestNameOfWithEventsSetterParameter",
<![CDATA[Public Class c1
Sub New()
goo = Me
End Sub
Public WithEvents goo As c1
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim verifier = CompileAndVerify(comp, expectedSignatures:=
{
Signature("c1", "goo", ".property readwrite instance c1 goo"),
Signature("c1", "set_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance System.Void set_goo(c1 WithEventsValue) cil managed synchronized"),
Signature("c1", "get_goo", ".method [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public newslot strict specialname virtual instance c1 get_goo() cil managed")
})
verifier.VerifyDiagnostics()
End Sub
<WorkItem(529548, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529548")>
<Fact()>
Public Sub TestIssueWeFixedInNativeCompiler()
Dim comp = CreateVisualBasicCompilation("TestIssueWeFixedInNativeCompiler",
<![CDATA[
Imports System
Interface I1(Of U)
Event E1(ByVal a As U)
End Interface
Class C1(Of T As {Exception, I1(Of T)})
Dim WithEvents x As T
'Native compiler used to report an incorrect error on the below line - "Method 'Public Sub goo(a As T)' cannot handle event 'Public Event E1(a As U)' because they do not have a compatible signature".
'This was a bug in the native compiler (see Bug: VSWhidbey/544224) that got fixed in Roslyn.
'See Vladimir's comments in bug 13489 for more details.
Sub goo(ByVal a As T) Handles x.E1
End Sub
Sub bar()
AddHandler x.E1, AddressOf goo 'AddHandler should also work
End Sub
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim verifier = CompileAndVerify(comp)
verifier.VerifyDiagnostics()
End Sub
<WorkItem(545188, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545188")>
<Fact>
Public Sub Bug13470()
Dim compilation1 = CompileAndVerify(
<compilation>
<file name="a.vb"><![CDATA[
Imports System
Class Program
Shared Sub Main()
Dim c1 = GetType(C1)
Dim _Goo = c1.GetField("_Goo", Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance)
Dim obsolete = _Goo.GetCustomAttributes(GetType(ObsoleteAttribute), False)
System.Console.WriteLine(obsolete.Length = 1)
End Sub
End Class
Class C1
<Obsolete> WithEvents Goo as C1
End Class
]]></file>
</compilation>, expectedOutput:="True")
End Sub
<WorkItem(545187, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545187")>
<Fact>
Public Sub Bug13469()
'Note: Below IL is for the following VB code compiled with Dev11 (using /debug-) -
'Public Class c1
' Sub New()
' goo = Me
' End Sub
' Public Event loo()
' Public WithEvents goo As C1
' Sub raise()
' RaiseEvent loo()
' End Sub
'End Class
Dim customIL = <![CDATA[
.class public auto ansi c1
extends [mscorlib]System.Object
{
.class auto ansi sealed nested public looEventHandler
extends [mscorlib]System.MulticastDelegate
{
.method public specialname rtspecialname
instance void .ctor(object TargetObject,
native int TargetMethod) runtime managed
{
} // end of method looEventHandler::.ctor
.method public newslot strict virtual
instance class [mscorlib]System.IAsyncResult
BeginInvoke(class [mscorlib]System.AsyncCallback DelegateCallback,
object DelegateAsyncState) runtime managed
{
} // end of method looEventHandler::BeginInvoke
.method public newslot strict virtual
instance void EndInvoke(class [mscorlib]System.IAsyncResult DelegateAsyncResult) runtime managed
{
} // end of method looEventHandler::EndInvoke
.method public newslot strict virtual
instance void Invoke() runtime managed
{
} // end of method looEventHandler::Invoke
} // end of class looEventHandler
.field private class c1/looEventHandler looEvent
.field private class c1 _goo
.custom instance void [mscorlib]System.Runtime.CompilerServices.AccessedThroughPropertyAttribute::.ctor(string) = ( 01 00 03 67 6F 6F 00 00 ) // ...goo..
.method public specialname rtspecialname
instance void .ctor() cil managed
{
// Code size 14 (0xe)
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void [mscorlib]System.Object::.ctor()
IL_0006: ldarg.0
IL_0007: ldarg.0
IL_0008: callvirt instance void c1::set_goo(class c1)
IL_000d: ret
} // end of method c1::.ctor
.method public specialname instance void
add_loo(class c1/looEventHandler obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class c1/looEventHandler c1::looEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Combine(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass c1/looEventHandler
IL_0012: stfld class c1/looEventHandler c1::looEvent
IL_0017: ret
} // end of method c1::add_loo
.method public specialname instance void
remove_loo(class c1/looEventHandler obj) cil managed synchronized
{
// Code size 24 (0x18)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.0
IL_0002: ldfld class c1/looEventHandler c1::looEvent
IL_0007: ldarg.1
IL_0008: call class [mscorlib]System.Delegate [mscorlib]System.Delegate::Remove(class [mscorlib]System.Delegate,
class [mscorlib]System.Delegate)
IL_000d: castclass c1/looEventHandler
IL_0012: stfld class c1/looEventHandler c1::looEvent
IL_0017: ret
} // end of method c1::remove_loo
.method public newslot specialname strict virtual
instance class c1 get_goo() cil managed
{
// Code size 11 (0xb)
.maxstack 1
.locals init (class c1 V_0)
IL_0000: ldarg.0
IL_0001: ldfld class c1 c1::_goo
IL_0006: stloc.0
IL_0007: br.s IL_0009
IL_0009: ldloc.0
IL_000a: ret
} // end of method c1::get_goo
.method public newslot specialname strict virtual
instance void set_goo(class c1 WithEventsValue) cil managed synchronized
{
// Code size 8 (0x8)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldarg.1
IL_0002: stfld class c1 c1::_goo
IL_0007: ret
} // end of method c1::set_goo
.method public instance void raise() cil managed
{
// Code size 17 (0x11)
.maxstack 1
.locals init (class c1/looEventHandler V_0)
IL_0000: ldarg.0
IL_0001: ldfld class c1/looEventHandler c1::looEvent
IL_0006: stloc.0
IL_0007: ldloc.0
IL_0008: brfalse.s IL_0010
IL_000a: ldloc.0
IL_000b: callvirt instance void c1/looEventHandler::Invoke()
IL_0010: ret
} // end of method c1::raise
.event c1/looEventHandler loo
{
.addon instance void c1::add_loo(class c1/looEventHandler)
.removeon instance void c1::remove_loo(class c1/looEventHandler)
} // end of event c1::loo
.property instance class c1 goo()
{
.get instance class c1 c1::get_goo()
.set instance void c1::set_goo(class c1)
} // end of property c1::goo
} // end of class c1
]]>
Dim compilation = CreateCompilationWithCustomILSource(
<compilation>
<file name="a.vb">
Imports System
Class c2
Inherits c1
Public res As Boolean = False
Sub test() Handles goo.loo 'here
res = True
End Sub
End Class
Public Module Program
Sub Main()
Dim c As New c2
c.goo.raise()
Console.WriteLine(c.res)
End Sub
End Module
</file>
</compilation>, customIL.Value, includeVbRuntime:=True, options:=TestOptions.ReleaseExe)
CompileAndVerify(compilation, expectedOutput:="True").VerifyDiagnostics()
End Sub
<Fact>
Public Sub SynthesizedOverridingWithEventsProperty()
Dim source =
<compilation>
<file>
Public Class Base
Protected Friend WithEvents w As Base = Me
Public Event e As System.Action
Sub H1() Handles w.e
End Sub
End Class
Public Class Derived
Inherits Base
Sub H2() Handles w.e
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250")>
Public Sub HookupOrder()
CompileAndVerify(
<compilation>
<file name="a.vb">
Imports System
Public Class Base
Protected Friend WithEvents w As Base = Me
Public Event e As Action(Of Integer)
Sub BaseH1() Handles w.e
Console.WriteLine(" BaseH1")
End Sub
Function BaseH2(ParamArray x() As Integer) Handles Me.e
Console.WriteLine(" BaseH2")
Return 0
End Function
Sub Raise()
RaiseEvent e(1)
End Sub
End Class
Public Class Derived
Inherits Base
Function DerivedH2(ParamArray x() As Integer) Handles Me.e
Console.WriteLine(" DerivedH2")
Return 0
End Function
Sub DerivedH1() Handles w.e
Console.WriteLine(" DerivedH1")
End Sub
End Class
Public Module Program
Sub Main()
Console.WriteLine("Base")
Dim x = New Base()
x.Raise()
Console.WriteLine("Derived")
x = New Derived
x.Raise()
End Sub
End Module
</file>
</compilation>, expectedOutput:=<![CDATA[Base
BaseH2
BaseH1
Derived
BaseH2
BaseH1
DerivedH1
DerivedH2
]]>)
End Sub
<Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")>
Public Sub TestExecutionOrder1()
Dim vbCompilation = CreateVisualBasicCompilation("TestExecutionOrder1",
<) Handles w.e, Me.e, MyClass.e
Console.WriteLine("7")
Return 1.0
End Function
Sub Raise3()
RaiseEvent e(Nothing)
End Sub
End Class
Public Module Program
Sub Main()
Dim x = New Derived(Of Base(Of ArgumentException, String, S, ArgumentException,
Dictionary(Of String, S), List(Of IList(Of ArgumentException))))
x.Raise()
x.Raise2()
x.w.Raise()
x.w2.Raise()
x.w2.Raise2()
x.Raise3()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication))
'Breaking Change: Dev11 processes event handlers in a different order than Roslyn.
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[2
4
3
5
7
2
6
5
5
7
7]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact, WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")>
Public Sub TestExecutionOrder2()
Dim assembly1Compilation = CreateVisualBasicCompilation("TestExecutionOrder2",
<![CDATA[Option Strict Off
Imports System, System.Runtime.CompilerServices
Imports AliasedType = Base
<Assembly: InternalsVisibleTo("Assembly2")>
Public Class Base
Protected WithEvents w As AliasedType = Me, x As Base = Me, y As Base = Me, z As New System.Collections.Generic.List(Of String) From {"123"}
Protected Friend Event e As Action(Of Integer)
Friend Sub H1() Handles w.e, x.e
Console.WriteLine("Base H1")
End Sub
Public Function H2(ParamArray x() As Integer) Handles x.e, w.e, Me.e, MyClass.e
Console.WriteLine("Base H2")
Return 0
End Function
Overridable Sub Raise()
RaiseEvent e(1)
End Sub
End Class
Public Class Base2 : Inherits Base
End Class]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
Dim assembly1Verifier = CompileAndVerify(assembly1Compilation)
assembly1Verifier.VerifyDiagnostics()
Dim assembly2Compilation = CreateVisualBasicCompilation("Assembly2",
<![CDATA[Imports System
Public Class Derived : Inherits Base2
Shadows Event e As Action(Of Exception)
Private Shadows Sub H1() Handles y.e, MyBase.e, x.e, w.e
Console.WriteLine("Derived H1")
End Sub
Protected Shadows Function H2(ParamArray x() As Integer) Handles MyBase.e
Console.WriteLine("Derived H2")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Console.WriteLine("Base")
Dim x = New Base()
x.Raise()
Console.WriteLine("Derived")
x = New Derived
x.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={assembly1Compilation})
'Breaking Change: Dev11 processes event handlers in a different order than Roslyn.
Dim assembly2Verifier = CompileAndVerify(assembly2Compilation,
expectedOutput:=<![CDATA[Base
Base H2
Base H2
Base H1
Base H2
Base H1
Base H2
Derived
Base H2
Base H2
Base H1
Base H2
Derived H1
Base H1
Base H2
Derived H1
Derived H1
Derived H1
Derived H2]]>)
assembly2Verifier.VerifyDiagnostics()
End Sub
<Fact(), WorkItem(545250, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545250"), WorkItem(529653, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529653")>
Public Sub TestCrossLanguageOptionalAndParamarray1()
Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray1_CS",
<![CDATA[public class CSClass
{
public delegate int bar(string x = "");
public event bar ev;
public void raise()
{
ev("BASE");
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray1_VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo(x As String) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED1")
Return 0
End Function
Function Goo(x As String, ParamArray y() As Integer) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED2")
Return 0
End Function
Function Goo2(Optional x As String = "") Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED3")
Return 0
End Function
Function Goo2(ParamArray x() As String) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED4")
Return 0
End Function
Function Goo2(x As String, Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED5")
Return 0
End Function
Function Goo3(Optional x As String = "", Optional y As Integer = 0) Handles w.ev, MyBase.ev, MyClass.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED6")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
'Breaking Change: Dev11 processes event handlers in a different order than Roslyn.
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[BASE
DERIVED1
BASE
DERIVED1
BASE
DERIVED2
BASE
DERIVED2
BASE
DERIVED3
BASE
DERIVED3
System.String[]
DERIVED4
System.String[]
DERIVED4
BASE
DERIVED5
BASE
DERIVED5
BASE
DERIVED6
BASE
DERIVED6
BASE
DERIVED1
BASE
DERIVED2
BASE
DERIVED3
System.String[]
DERIVED4
BASE
DERIVED5
BASE
DERIVED6]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestCrossLanguageOptionalAndPAramarray2()
Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndPAramarray2_CS",
<![CDATA[public class CSClass
{
public delegate int bar(params int[] y);
public event bar ev;
public void raise()
{
ev(1, 2, 3);
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndPAramarray2_VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo(x As Integer()) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED1")
Return 0
End Function
Function Goo2(ParamArray x As Integer()) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED2")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
Dim vbVerifier = CompileAndVerify(vbCompilation,
expectedOutput:=<![CDATA[System.Int32[]
DERIVED1
System.Int32[]
DERIVED1
System.Int32[]
DERIVED2
System.Int32[]
DERIVED2
System.Int32[]
DERIVED1
System.Int32[]
DERIVED2]]>)
vbVerifier.VerifyDiagnostics()
End Sub
<Fact>
Public Sub TestCrossLanguageOptionalAndParamarray_Error1()
Dim csCompilation = CreateCSharpCompilation("TestCrossLanguageOptionalAndParamarray_Error1_CS",
<![CDATA[public class CSClass
{
public delegate int bar(params int[] y);
public event bar ev;
public void raise()
{
ev(1, 2, 3);
}
}]]>,
compilationOptions:=New Microsoft.CodeAnalysis.CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("TestCrossLanguageOptionalAndParamarray_Error1_VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo2(x As Integer) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED1")
Return 0
End Function
Function Goo2(x As Integer, Optional y As Integer = 1) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("DERIVED2")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo2", "ev"))
End Sub
<Fact, WorkItem(545257, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545257")>
Public Sub TestCrossLanguageOptionalAndParamarray_Error2()
Dim csCompilation = CreateCSharpCompilation("CS",
<![CDATA[public class CSClass
{
public delegate int bar(params int[] y);
public event bar ev;
public void raise()
{
ev(1, 2, 3);
}
}]]>,
compilationOptions:=New CSharp.CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
csCompilation.VerifyDiagnostics()
Dim vbCompilation = CreateVisualBasicCompilation("VB",
<![CDATA[Imports System
Public Class VBClass : Inherits CSClass
Public WithEvents w As CSClass = New CSClass
Function Goo(Optional x As Integer = 1) Handles w.ev, MyBase.ev, Me.ev
Console.WriteLine(x)
Console.WriteLine("PASS")
Return 0
End Function
End Class
Public Module Program
Sub Main()
Dim x = New VBClass
x.raise()
x.w.Raise()
End Sub
End Module]]>,
compilationOptions:=New VisualBasicCompilationOptions(OutputKind.ConsoleApplication),
referencedCompilations:={csCompilation})
vbCompilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"),
Diagnostic(ERRID.ERR_EventHandlerSignatureIncompatible2, "ev").WithArguments("Goo", "ev"))
End Sub
<Fact>
Public Sub DelegateRelaxationStubsUniqueNaming1()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class WE
Event V As Action(Of Integer, Integer)
Event W As Action(Of Long, Long)
End Class
Class B
Public WithEvents A3 As WE
End Class
Class D
Inherits B
Public WithEvents A1 As WE
Public WithEvents A2 As WE
End Class
Class E
Inherits D
Sub G(z1 As Double, z2 As Double) Handles A1.V, A3.W
Console.WriteLine(z1 + z2)
End Sub
Sub G(z1 As Double, z2 As Integer) Handles A1.V, A3.W
Console.WriteLine(z1 + z2)
End Sub
Sub G(z1 As Integer, z2 As Double) Handles A2.V, A3.W, A1.V
Console.WriteLine(z1 + z2)
End Sub
Sub G(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V
Console.WriteLine(z1 + z2)
End Sub
Sub F(z1 As Byte, z2 As Integer) Handles A2.V, A3.W, A1.V
Console.WriteLine(z1 + z2)
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact>
Public Sub DelegateRelaxationStubsUniqueNaming2()
Dim source =
<compilation>
<file name="a.vb">
Imports System
Class WE
Public Event V1 As Action(Of Integer)
Public Event V2 As Action(Of Integer)
End Class
Class B
Public WithEvents we As WE = New WE
Public Event W1 As Action(Of Integer)
Public Event W2 As Action(Of Integer)
End Class
Class C
Inherits B
Public Event U1 As Action(Of Integer)
Public Event U2 As Action(Of Integer)
Sub F() Handles we.V1, we.V2, MyBase.W1, MyBase.W2, Me.U1, Me.U2
End Sub
End Class
</file>
</compilation>
CompileAndVerify(source)
End Sub
<Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")>
Public Sub MultipleInitializationsWithAsNew_01()
Dim source =
<compilation>
<file name="a.vb">
Class C1
Shared WithEvents a1, b1, c1 As New C2()
WithEvents a2, b2, c2 As New C2()
Shared a3, b3, c3 As New C2()
Dim a4, b4, c4 As New C2()
Shared Sub Main()
Check(a1, b1, c1)
Check(a3, b3, c3)
Dim c as New C1()
Check(c.a2, c.b2, c.c2)
Check(c.a4, c.b4, c.c4)
End Sub
Private Shared Sub Check(a As Object, b As Object, c As Object)
System.Console.WriteLine(a Is Nothing)
System.Console.WriteLine(b Is Nothing)
System.Console.WriteLine(c Is Nothing)
System.Console.WriteLine(a Is b)
System.Console.WriteLine(a Is c)
System.Console.WriteLine(b Is c)
End Sub
End Class
Class C2
End Class
</file>
</compilation>
CompileAndVerify(source, expectedOutput:=
<![CDATA[
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
False
]]>)
End Sub
<Fact, WorkItem(4544, "https://github.com/dotnet/roslyn/issues/4544")>
Public Sub MultipleInitializationsWithAsNew_02()
Dim source =
<compilation>
<file name="a.vb">
Class C1
Shared WithEvents a, b, c As New C1() With {.P1 = 2}
Shared Sub Main()
System.Console.WriteLine(a.P1)
System.Console.WriteLine(b.P1)
System.Console.WriteLine(c.P1)
System.Console.WriteLine(a Is b)
System.Console.WriteLine(a Is c)
System.Console.WriteLine(b Is c)
End Sub
Public P1 As Integer
End Class
</file>
</compilation>
CompileAndVerify(source, expectedOutput:=
<![CDATA[
2
2
2
False
False
False
]]>).
VerifyIL("C1..cctor",
<![CDATA[
{
// Code size 52 (0x34)
.maxstack 3
IL_0000: newobj "Sub C1..ctor()"
IL_0005: dup
IL_0006: ldc.i4.2
IL_0007: stfld "C1.P1 As Integer"
IL_000c: call "Sub C1.set_a(C1)"
IL_0011: newobj "Sub C1..ctor()"
IL_0016: dup
IL_0017: ldc.i4.2
IL_0018: stfld "C1.P1 As Integer"
IL_001d: call "Sub C1.set_b(C1)"
IL_0022: newobj "Sub C1..ctor()"
IL_0027: dup
IL_0028: ldc.i4.2
IL_0029: stfld "C1.P1 As Integer"
IL_002e: call "Sub C1.set_c(C1)"
IL_0033: ret
}
]]>)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Errors/SyntaxDiagnosticInfo.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal class SyntaxDiagnosticInfo : DiagnosticInfo
{
static SyntaxDiagnosticInfo()
{
ObjectBinder.RegisterTypeReader(typeof(SyntaxDiagnosticInfo), r => new SyntaxDiagnosticInfo(r));
}
internal readonly int Offset;
internal readonly int Width;
internal SyntaxDiagnosticInfo(int offset, int width, ErrorCode code, params object[] args)
: base(CSharp.MessageProvider.Instance, (int)code, args)
{
Debug.Assert(width >= 0);
this.Offset = offset;
this.Width = width;
}
internal SyntaxDiagnosticInfo(int offset, int width, ErrorCode code)
: this(offset, width, code, Array.Empty<object>())
{
}
internal SyntaxDiagnosticInfo(ErrorCode code, params object[] args)
: this(0, 0, code, args)
{
}
internal SyntaxDiagnosticInfo(ErrorCode code)
: this(0, 0, code)
{
}
public SyntaxDiagnosticInfo WithOffset(int offset)
{
return new SyntaxDiagnosticInfo(offset, this.Width, (ErrorCode)this.Code, this.Arguments);
}
#region Serialization
protected override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteInt32(this.Offset);
writer.WriteInt32(this.Width);
}
protected SyntaxDiagnosticInfo(ObjectReader reader)
: base(reader)
{
this.Offset = reader.ReadInt32();
this.Width = reader.ReadInt32();
}
#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;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal class SyntaxDiagnosticInfo : DiagnosticInfo
{
static SyntaxDiagnosticInfo()
{
ObjectBinder.RegisterTypeReader(typeof(SyntaxDiagnosticInfo), r => new SyntaxDiagnosticInfo(r));
}
internal readonly int Offset;
internal readonly int Width;
internal SyntaxDiagnosticInfo(int offset, int width, ErrorCode code, params object[] args)
: base(CSharp.MessageProvider.Instance, (int)code, args)
{
Debug.Assert(width >= 0);
this.Offset = offset;
this.Width = width;
}
internal SyntaxDiagnosticInfo(int offset, int width, ErrorCode code)
: this(offset, width, code, Array.Empty<object>())
{
}
internal SyntaxDiagnosticInfo(ErrorCode code, params object[] args)
: this(0, 0, code, args)
{
}
internal SyntaxDiagnosticInfo(ErrorCode code)
: this(0, 0, code)
{
}
public SyntaxDiagnosticInfo WithOffset(int offset)
{
return new SyntaxDiagnosticInfo(offset, this.Width, (ErrorCode)this.Code, this.Arguments);
}
#region Serialization
protected override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteInt32(this.Offset);
writer.WriteInt32(this.Width);
}
protected SyntaxDiagnosticInfo(ObjectReader reader)
: base(reader)
{
this.Offset = reader.ReadInt32();
this.Width = reader.ReadInt32();
}
#endregion
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/VisualBasic/Impl/CodeModel/VisualBasicCodeModelService.NodeLocator.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
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
Partial Friend Class VisualBasicCodeModelService
Protected Overrides Function CreateNodeLocator() As AbstractNodeLocator
Return New NodeLocator()
End Function
Private Class NodeLocator
Inherits AbstractNodeLocator
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Protected Overrides ReadOnly Property DefaultPart As EnvDTE.vsCMPart
Get
Return EnvDTE.vsCMPart.vsCMPartWhole
End Get
End Property
Protected Overrides Function GetStartPoint(text As SourceText, options As OptionSet, node As SyntaxNode, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return GetTypeBlockStartPoint(text, options, DirectCast(node, TypeBlockSyntax), part)
Case SyntaxKind.EnumBlock
Return GetEnumBlockStartPoint(text, options, DirectCast(node, EnumBlockSyntax), part)
Case SyntaxKind.ClassStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.StructureStatement
Return GetTypeBlockStartPoint(text, options, DirectCast(node.Parent, TypeBlockSyntax), part)
Case SyntaxKind.EnumStatement
Return GetEnumBlockStartPoint(text, options, DirectCast(node.Parent, EnumBlockSyntax), part)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetMethodBlockStartPoint(text, options, DirectCast(node, MethodBlockBaseSyntax), part)
Case SyntaxKind.SubNewStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerStatement,
SyntaxKind.RemoveHandlerStatement,
SyntaxKind.RaiseEventStatement
Return GetMethodBlockStartPoint(text, options, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
If TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return GetMethodBlockStartPoint(text, options, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Else
Return GetMethodStatementStartPoint(text, DirectCast(node, MethodStatementSyntax), part)
End If
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return GetDeclareStatementStartPoint(text, DirectCast(node, DeclareStatementSyntax), part)
Case SyntaxKind.PropertyBlock
Return GetPropertyBlockStartPoint(text, DirectCast(node, PropertyBlockSyntax), part)
Case SyntaxKind.PropertyStatement
Return GetPropertyStatementStartPoint(text, DirectCast(node, PropertyStatementSyntax), part)
Case SyntaxKind.EventBlock
Return GetEventBlockStartPoint(text, options, DirectCast(node, EventBlockSyntax), part)
Case SyntaxKind.EventStatement
Return GetEventStatementStartPoint(text, DirectCast(node, EventStatementSyntax), part)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return GetDelegateStatementStartPoint(text, DirectCast(node, DelegateStatementSyntax), part)
Case SyntaxKind.NamespaceBlock
Return GetNamespaceBlockStartPoint(text, options, DirectCast(node, NamespaceBlockSyntax), part)
Case SyntaxKind.NamespaceStatement
Return GetNamespaceBlockStartPoint(text, options, DirectCast(node.Parent, NamespaceBlockSyntax), part)
Case SyntaxKind.ModifiedIdentifier
Return GetVariableStartPoint(text, DirectCast(node, ModifiedIdentifierSyntax), part)
Case SyntaxKind.EnumMemberDeclaration
Return GetVariableStartPoint(text, DirectCast(node, EnumMemberDeclarationSyntax), part)
Case SyntaxKind.Parameter
Return GetParameterStartPoint(text, DirectCast(node, ParameterSyntax), part)
Case SyntaxKind.Attribute
Return GetAttributeStartPoint(text, DirectCast(node, AttributeSyntax), part)
Case SyntaxKind.SimpleArgument,
SyntaxKind.OmittedArgument
Return GetAttributeArgumentStartPoint(text, DirectCast(node, ArgumentSyntax), part)
Case SyntaxKind.SimpleImportsClause
Return GetImportsStatementStartPoint(text, DirectCast(node.Parent, ImportsStatementSyntax), part)
Case SyntaxKind.OptionStatement
Return GetOptionStatementStartPoint(text, DirectCast(node, OptionStatementSyntax), part)
Case SyntaxKind.InheritsStatement
Return GetInheritsStatementStartPoint(text, DirectCast(node, InheritsStatementSyntax), part)
Case SyntaxKind.ImplementsStatement
Return GetImplementsStatementStartPoint(text, DirectCast(node, ImplementsStatementSyntax), part)
Case Else
Debug.Fail(String.Format("Unsupported node kind: {0}", CType(node.Kind, SyntaxKind)))
Throw New NotSupportedException()
End Select
End Function
Protected Overrides Function GetEndPoint(text As SourceText, options As OptionSet, node As SyntaxNode, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return GetTypeBlockEndPoint(text, DirectCast(node, TypeBlockSyntax), part)
Case SyntaxKind.EnumBlock
Return GetEnumBlockEndPoint(text, DirectCast(node, EnumBlockSyntax), part)
Case SyntaxKind.ClassStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return GetTypeBlockEndPoint(text, DirectCast(node.Parent, TypeBlockSyntax), part)
Case SyntaxKind.EnumStatement
Return GetEnumBlockEndPoint(text, DirectCast(node.Parent, EnumBlockSyntax), part)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetMethodBlockEndPoint(text, DirectCast(node, MethodBlockBaseSyntax), part)
Case SyntaxKind.SubNewStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerStatement,
SyntaxKind.RemoveHandlerStatement,
SyntaxKind.RaiseEventStatement
Return GetMethodBlockEndPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
If TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return GetMethodBlockEndPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Else
Return GetMethodStatementEndPoint(text, DirectCast(node, MethodStatementSyntax), part)
End If
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return GetDeclareStatementEndPoint(text, DirectCast(node, DeclareStatementSyntax), part)
Case SyntaxKind.PropertyBlock
Return GetPropertyBlockEndPoint(text, DirectCast(node, PropertyBlockSyntax), part)
Case SyntaxKind.PropertyStatement
Return GetPropertyStatementEndPoint(text, DirectCast(node, PropertyStatementSyntax), part)
Case SyntaxKind.EventBlock
Return GetEventBlockEndPoint(text, DirectCast(node, EventBlockSyntax), part)
Case SyntaxKind.EventStatement
Return GetEventStatementEndPoint(text, DirectCast(node, EventStatementSyntax), part)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return GetDelegateStatementEndPoint(text, DirectCast(node, DelegateStatementSyntax), part)
Case SyntaxKind.NamespaceBlock
Return GetNamespaceBlockEndPoint(text, DirectCast(node, NamespaceBlockSyntax), part)
Case SyntaxKind.NamespaceStatement
Return GetNamespaceBlockEndPoint(text, DirectCast(node.Parent, NamespaceBlockSyntax), part)
Case SyntaxKind.ModifiedIdentifier
Return GetVariableEndPoint(text, DirectCast(node, ModifiedIdentifierSyntax), part)
Case SyntaxKind.EnumMemberDeclaration
Return GetVariableEndPoint(text, DirectCast(node, EnumMemberDeclarationSyntax), part)
Case SyntaxKind.Parameter
Return GetParameterEndPoint(text, DirectCast(node, ParameterSyntax), part)
Case SyntaxKind.Attribute
Return GetAttributeEndPoint(text, DirectCast(node, AttributeSyntax), part)
Case SyntaxKind.SimpleArgument,
SyntaxKind.OmittedArgument
Return GetAttributeArgumentEndPoint(text, DirectCast(node, ArgumentSyntax), part)
Case SyntaxKind.SimpleImportsClause
Return GetImportsStatementEndPoint(text, DirectCast(node.Parent, ImportsStatementSyntax), part)
Case SyntaxKind.OptionStatement
Return GetOptionStatementEndPoint(text, DirectCast(node, OptionStatementSyntax), part)
Case SyntaxKind.InheritsStatement
Return GetInheritsStatementEndPoint(text, DirectCast(node, InheritsStatementSyntax), part)
Case SyntaxKind.ImplementsStatement
Return GetImplementsStatementEndPoint(text, DirectCast(node, ImplementsStatementSyntax), part)
Case Else
Debug.Fail(String.Format("Unsupported node kind: {0}", CType(node.Kind, SyntaxKind)))
Throw New NotImplementedException()
End Select
End Function
Private Function GetAttributesStartPoint(text As SourceText, attributes As SyntaxList(Of AttributeListSyntax), part As EnvDTE.vsCMPart) As VirtualTreePoint?
' VB has a Code Model bug that causes vsCMPartAttributes and vsCMPartAttributesWithDelimiters to return the same value.
' You can see the issue clearly in vb\Language\VsPackage\CodeModelHelpers.cpp, CodeModelLocations::GetAttributeSpecifierListLocation.
' Essentially, the old code tries to do the right thing for vsCMPartAttributes, but then deliberately falls through to the
' vsCMPartAttributesWithDelimiter case, where it overwrites the calculation it just made. Sigh...
If attributes.Count = 0 Then
Return Nothing
End If
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
startPosition = attributes.First().LessThanToken.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Return Nothing
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attributes.First().SyntaxTree, text, startPosition)
End Function
Private Function GetAttributesEndPoint(text As SourceText, attributes As SyntaxList(Of AttributeListSyntax), part As EnvDTE.vsCMPart) As VirtualTreePoint?
' VB has a Code Model bug that causes vsCMPartAttributes and vsCMPartAttributesWithDelimiters to return the same value.
' See GetAttributesStartPoint for the details
If attributes.Count = 0 Then
Return Nothing
End If
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
startPosition = attributes.Last().GreaterThanToken.Span.End
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Return Nothing
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attributes.Last().SyntaxTree, text, startPosition)
End Function
Private Function GetHeaderStartPosition(typeBlock As TypeBlockSyntax) As Integer
If typeBlock.BlockStatement.Modifiers.Count > 0 Then
Return typeBlock.BlockStatement.Modifiers.First().SpanStart
Else
Return typeBlock.BlockStatement.DeclarationKeyword.SpanStart
End If
End Function
Private Function GetHeaderStartPosition(enumBlock As EnumBlockSyntax) As Integer
If enumBlock.EnumStatement.Modifiers.Count > 0 Then
Return enumBlock.EnumStatement.Modifiers.First().SpanStart
Else
Return enumBlock.EnumStatement.EnumKeyword.SpanStart
End If
End Function
Private Function GetTypeBlockStartPoint(text As SourceText, options As OptionSet, typeBlock As TypeBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = typeBlock.BlockStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, typeBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = typeBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = GetHeaderStartPosition(typeBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim statement As StatementSyntax = typeBlock.BlockStatement
While statement IsNot Nothing
Dim [next] = statement.GetNextNonEmptyStatement()
If [next] IsNot Nothing AndAlso
([next].Kind = SyntaxKind.InheritsStatement OrElse
[next].Kind = SyntaxKind.ImplementsStatement) Then
statement = [next]
Continue While
Else
Exit While
End If
End While
Debug.Assert(statement IsNot Nothing)
Dim statementLine = text.Lines.GetLineFromPosition(statement.SpanStart)
' statement points to either the last Inherits/Implements or to the type declaration itself.
Dim nextStatement = statement.GetNextNonEmptyStatement()
Dim nextStatementLine As Nullable(Of TextLine) = If(nextStatement IsNot Nothing, text.Lines.GetLineFromPosition(nextStatement.SpanStart), Nothing)
' If the next statement is on the same line as the current one, set body start
' position to the end of the current statement
If nextStatementLine IsNot Nothing AndAlso nextStatementLine.Value.LineNumber = statementLine.LineNumber Then
startPosition = statement.Span.End
Else
' Otherwise, use the beginning of the next line.
startPosition = text.Lines(statementLine.LineNumber + 1).Start
End If
If part = EnvDTE.vsCMPart.vsCMPartNavigate Then
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), typeBlock.BlockStatement, statementLine.LineNumber + 1)
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(typeBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetTypeBlockEndPoint(text As SourceText, typeBlock As TypeBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = typeBlock.BlockStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, typeBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = typeBlock.BlockStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = typeBlock.Span.End
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = typeBlock.EndBlockStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(typeBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetEnumBlockStartPoint(text As SourceText, options As OptionSet, enumBlock As EnumBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = enumBlock.EnumStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, enumBlock.EnumStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = enumBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = GetHeaderStartPosition(enumBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim statement As StatementSyntax = enumBlock.EnumStatement
Dim statementLine = text.Lines.GetLineFromPosition(statement.SpanStart)
Dim nextStatement = statement.GetNextNonEmptyStatement()
Dim nextStatementLine As Nullable(Of TextLine) = If(nextStatement IsNot Nothing, text.Lines.GetLineFromPosition(nextStatement.SpanStart), Nothing)
' If the next statement is on the same line as the current one, set body start
' position to the end of the current statement
If nextStatementLine IsNot Nothing AndAlso nextStatementLine.Value.LineNumber = statementLine.LineNumber Then
startPosition = statement.Span.End
Else
' Otherwise, use the beginning of the next line.
startPosition = text.Lines(statementLine.LineNumber + 1).Start
End If
If part = EnvDTE.vsCMPart.vsCMPartNavigate Then
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), enumBlock.EnumStatement, statementLine.LineNumber + 1)
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetEnumBlockEndPoint(text As SourceText, enumBlock As EnumBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = enumBlock.EnumStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, enumBlock.EnumStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = enumBlock.EnumStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = enumBlock.Span.End
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = enumBlock.EndEnumStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetMethodBlockStartPoint(text As SourceText, options As OptionSet, methodBlock As MethodBlockBaseSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
Select Case methodBlock.BlockStatement.Kind
Case SyntaxKind.SubNewStatement
startPosition = DirectCast(methodBlock.BlockStatement, SubNewStatementSyntax).NewKeyword.SpanStart
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
startPosition = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier.SpanStart
Case SyntaxKind.OperatorStatement
startPosition = DirectCast(methodBlock.BlockStatement, OperatorStatementSyntax).OperatorToken.SpanStart
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
' For properties accessors, use the name of property block
Dim propertyBlock = methodBlock.FirstAncestorOrSelf(Of PropertyBlockSyntax)()
If propertyBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetPropertyBlockStartPoint(text, propertyBlock, part)
Case SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' For event accessors, use the name of event block
Dim eventBlock = methodBlock.FirstAncestorOrSelf(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetEventBlockStartPoint(text, options, eventBlock, part)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, methodBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = methodBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = NavigationPointHelpers.GetHeaderStartPosition(methodBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), methodBlock)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim startLine = text.Lines.GetLineFromPosition(NavigationPointHelpers.GetHeaderStartPosition(methodBlock))
startPosition = text.Lines(startLine.LineNumber + 1).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetDeclareStatementStartPoint(text As SourceText, declareStatement As DeclareStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = declareStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, declareStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If declareStatement.AttributeLists.Count > 0 Then
startPosition = declareStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = declareStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = declareStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(declareStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetDeclareStatementEndPoint(text As SourceText, declareStatement As DeclareStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = declareStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, declareStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = declareStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(declareStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetMethodStatementStartPoint(text As SourceText, methodStatement As MethodStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = methodStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, methodStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If methodStatement.AttributeLists.Count > 0 Then
startPosition = methodStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = methodStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = methodStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetMethodBlockEndPoint(text As SourceText, methodBlock As MethodBlockBaseSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
Select Case methodBlock.BlockStatement.Kind
Case SyntaxKind.SubNewStatement
startPosition = DirectCast(methodBlock.BlockStatement, SubNewStatementSyntax).NewKeyword.Span.End
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
startPosition = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier.Span.End
Case SyntaxKind.OperatorStatement
startPosition = DirectCast(methodBlock.BlockStatement, OperatorStatementSyntax).OperatorToken.Span.End
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
' For properties accessors, use the name of property block
Dim propertyBlock = methodBlock.FirstAncestorOrSelf(Of PropertyBlockSyntax)()
If propertyBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetPropertyBlockEndPoint(text, propertyBlock, part)
Case SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' For event accessors, use the name of event block
Dim eventBlock = methodBlock.FirstAncestorOrSelf(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetEventBlockEndPoint(text, eventBlock, part)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, methodBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = methodBlock.BlockStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = methodBlock.Span.End
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = methodBlock.EndBlockStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetMethodStatementEndPoint(text As SourceText, methodStatement As MethodStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = methodStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, methodStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = methodStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetPropertyBlockStartPoint(text As SourceText, propertyBlock As PropertyBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Return GetPropertyStatementStartPoint(text, propertyBlock.PropertyStatement, part)
End Function
Private Function GetPropertyStatementStartPoint(text As SourceText, propertyStatement As PropertyStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = propertyStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, propertyStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
If propertyStatement.AttributeLists.Count > 0 Then
startPosition = propertyStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = propertyStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = propertyStatement.SpanStart
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim beginLine = text.Lines.IndexOf(propertyStatement.Span.End)
Dim lineNumber = beginLine + 1
startPosition = text.Lines(lineNumber).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(propertyStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetPropertyBlockEndPoint(text As SourceText, propertyBlock As PropertyBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Return GetPropertyStatementEndPoint(text, propertyBlock.PropertyStatement, part)
End Function
Private Function GetPropertyStatementEndPoint(text As SourceText, propertyStatement As PropertyStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = propertyStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, propertyStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = propertyStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = If(propertyStatement.IsParentKind(SyntaxKind.PropertyBlock),
DirectCast(propertyStatement.Parent, PropertyBlockSyntax).EndPropertyStatement.Span.End,
propertyStatement.Span.End)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
EnvDTE.vsCMPart.vsCMPartNavigate
' Oddity of VB code model: this only happens if it isn't an auto-property. Otherwise, the start of the file is returned.
startPosition = If(propertyStatement.IsParentKind(SyntaxKind.PropertyBlock),
DirectCast(propertyStatement.Parent, PropertyBlockSyntax).EndPropertyStatement.SpanStart,
0)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(propertyStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetEventBlockStartPoint(text As SourceText, options As OptionSet, eventBlock As EventBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = eventBlock.EventStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, eventBlock.EventStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = eventBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = NavigationPointHelpers.GetHeaderStartPosition(eventBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), eventBlock)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim startLine = text.Lines.GetLineFromPosition(NavigationPointHelpers.GetHeaderStartPosition(eventBlock))
startPosition = text.Lines(startLine.LineNumber + 1).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(eventBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetEventStatementStartPoint(text As SourceText, eventStatement As EventStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = eventStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, eventStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If eventStatement.AttributeLists.Count > 0 Then
startPosition = eventStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = eventStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = eventStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(eventStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetEventBlockEndPoint(text As SourceText, eventBlock As EventBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Return GetEventStatementEndPoint(text, eventBlock.EventStatement, part)
End Function
Private Function GetEventStatementEndPoint(text As SourceText, eventStatement As EventStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = eventStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, eventStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = eventStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = If(eventStatement.IsParentKind(SyntaxKind.EventBlock),
DirectCast(eventStatement.Parent, EventBlockSyntax).EndEventStatement.Span.End,
eventStatement.Span.End)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
EnvDTE.vsCMPart.vsCMPartNavigate
startPosition = If(eventStatement.IsParentKind(SyntaxKind.EventBlock),
DirectCast(eventStatement.Parent, EventBlockSyntax).EndEventStatement.SpanStart,
eventStatement.Span.End)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(eventStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetDelegateStatementStartPoint(text As SourceText, delegateStatement As DelegateStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = delegateStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, delegateStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If delegateStatement.AttributeLists.Count > 0 Then
startPosition = delegateStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = delegateStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = delegateStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(delegateStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetDelegateStatementEndPoint(text As SourceText, delegateStatement As DelegateStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = delegateStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, delegateStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = delegateStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(delegateStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetTrailingColonTrivia(statement As StatementSyntax) As SyntaxTrivia?
If Not statement.HasTrailingTrivia Then
Return Nothing
End If
Return statement _
.GetTrailingTrivia() _
.FirstOrNull(Function(t) t.Kind = SyntaxKind.ColonTrivia)
End Function
Private Function GetNamespaceBlockStartPoint(text As SourceText, options As OptionSet, namespaceBlock As NamespaceBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = namespaceBlock.NamespaceStatement.Name.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = namespaceBlock.NamespaceStatement.SpanStart
Case EnvDTE.vsCMPart.vsCMPartNavigate
Dim beginStatement = namespaceBlock.NamespaceStatement
Dim beginLine = text.Lines.IndexOf(beginStatement.SpanStart)
Dim lineNumber = beginLine + 1
' If the begin statement has trailing colon trivia, we assume the body starts at the colon.
Dim colonTrivia = GetTrailingColonTrivia(beginStatement)
If colonTrivia IsNot Nothing Then
lineNumber = text.Lines.IndexOf(colonTrivia.Value.SpanStart)
End If
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), namespaceBlock.NamespaceStatement, lineNumber)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim beginStatement = namespaceBlock.NamespaceStatement
Dim endStatement = namespaceBlock.EndNamespaceStatement
' Handle case where begin statement has trailing colon trivia, e.g. Namespace N : End Namespace
Dim colonTrivia = GetTrailingColonTrivia(beginStatement)
If colonTrivia IsNot Nothing Then
startPosition = colonTrivia.Value.SpanStart
Exit Select
End If
Dim beginLine = text.Lines.IndexOf(beginStatement.SpanStart)
Dim lineNumber = beginLine + 1
startPosition = text.Lines(lineNumber).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(namespaceBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetNamespaceBlockEndPoint(text As SourceText, namespaceBlock As NamespaceBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = namespaceBlock.NamespaceStatement.Name.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader
endPosition = namespaceBlock.NamespaceStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole
endPosition = namespaceBlock.EndNamespaceStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
EnvDTE.vsCMPart.vsCMPartNavigate
endPosition = namespaceBlock.EndNamespaceStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(namespaceBlock.SyntaxTree, text, endPosition)
End Function
Private Function GetVariableStartPoint(text As SourceText, variable As ModifiedIdentifierSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim fieldDeclaration = variable.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
Debug.Assert(fieldDeclaration IsNot Nothing)
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = variable.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, fieldDeclaration.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = fieldDeclaration.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If fieldDeclaration.Modifiers.Count > 0 Then
startPosition = fieldDeclaration.Modifiers.First().SpanStart
Else
startPosition = fieldDeclaration.Declarators.First().SpanStart
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(variable.SyntaxTree, text, startPosition)
End Function
Private Function GetVariableStartPoint(text As SourceText, enumMember As EnumMemberDeclarationSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = enumMember.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, enumMember.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = enumMember.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = enumMember.Identifier.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumMember.SyntaxTree, text, startPosition)
End Function
Private Function GetVariableEndPoint(text As SourceText, variable As ModifiedIdentifierSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim fieldDeclaration = variable.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
Debug.Assert(fieldDeclaration IsNot Nothing)
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = variable.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, fieldDeclaration.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = fieldDeclaration.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(variable.SyntaxTree, text, endPosition)
End Function
Private Function GetVariableEndPoint(text As SourceText, enumMember As EnumMemberDeclarationSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = enumMember.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, enumMember.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = enumMember.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumMember.SyntaxTree, text, endPosition)
End Function
Private Function GetParameterStartPoint(text As SourceText, parameter As ParameterSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = parameter.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, parameter.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = parameter.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If parameter.Modifiers.Any() Then
startPosition = parameter.Modifiers.First().SpanStart
Else
startPosition = parameter.Identifier.SpanStart
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(parameter.SyntaxTree, text, startPosition)
End Function
Private Function GetParameterEndPoint(text As SourceText, parameter As ParameterSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = parameter.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, parameter.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = parameter.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(parameter.SyntaxTree, text, endPosition)
End Function
Private Function GetImportsStatementStartPoint(text As SourceText, importsStatement As ImportsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = importsStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(importsStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetImportsStatementEndPoint(text As SourceText, importsStatement As ImportsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = importsStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(importsStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetOptionStatementStartPoint(text As SourceText, optionStatement As OptionStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = optionStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(optionStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetOptionStatementEndPoint(text As SourceText, optionStatement As OptionStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = optionStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(optionStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetInheritsStatementStartPoint(text As SourceText, inheritsStatement As InheritsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = inheritsStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(inheritsStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetInheritsStatementEndPoint(text As SourceText, inheritsStatement As InheritsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = inheritsStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(inheritsStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetImplementsStatementStartPoint(text As SourceText, implementsStatement As ImplementsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = implementsStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(implementsStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetImplementsStatementEndPoint(text As SourceText, implementsStatement As ImplementsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = implementsStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(implementsStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetAttributeStartPoint(text As SourceText, attribute As AttributeSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = attribute.Name.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = attribute.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attribute.SyntaxTree, text, startPosition)
End Function
Private Function GetAttributeEndPoint(text As SourceText, attribute As AttributeSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = attribute.Name.Span.End
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = attribute.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attribute.SyntaxTree, text, endPosition)
End Function
Private Function GetAttributeArgumentStartPoint(text As SourceText, argument As ArgumentSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
If Not argument.IsNamed Then
Return Nothing
End If
startPosition = DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = If(argument.Kind = SyntaxKind.OmittedArgument,
argument.SpanStart - 1,
argument.SpanStart)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(argument.SyntaxTree, text, startPosition)
End Function
Private Function GetAttributeArgumentEndPoint(text As SourceText, argument As ArgumentSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
If Not argument.IsNamed Then
Return Nothing
End If
endPosition = DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Span.End
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = argument.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(argument.SyntaxTree, text, endPosition)
End Function
End Class
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel
Partial Friend Class VisualBasicCodeModelService
Protected Overrides Function CreateNodeLocator() As AbstractNodeLocator
Return New NodeLocator()
End Function
Private Class NodeLocator
Inherits AbstractNodeLocator
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Protected Overrides ReadOnly Property DefaultPart As EnvDTE.vsCMPart
Get
Return EnvDTE.vsCMPart.vsCMPartWhole
End Get
End Property
Protected Overrides Function GetStartPoint(text As SourceText, options As OptionSet, node As SyntaxNode, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return GetTypeBlockStartPoint(text, options, DirectCast(node, TypeBlockSyntax), part)
Case SyntaxKind.EnumBlock
Return GetEnumBlockStartPoint(text, options, DirectCast(node, EnumBlockSyntax), part)
Case SyntaxKind.ClassStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleStatement,
SyntaxKind.StructureStatement
Return GetTypeBlockStartPoint(text, options, DirectCast(node.Parent, TypeBlockSyntax), part)
Case SyntaxKind.EnumStatement
Return GetEnumBlockStartPoint(text, options, DirectCast(node.Parent, EnumBlockSyntax), part)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetMethodBlockStartPoint(text, options, DirectCast(node, MethodBlockBaseSyntax), part)
Case SyntaxKind.SubNewStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerStatement,
SyntaxKind.RemoveHandlerStatement,
SyntaxKind.RaiseEventStatement
Return GetMethodBlockStartPoint(text, options, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
If TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return GetMethodBlockStartPoint(text, options, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Else
Return GetMethodStatementStartPoint(text, DirectCast(node, MethodStatementSyntax), part)
End If
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return GetDeclareStatementStartPoint(text, DirectCast(node, DeclareStatementSyntax), part)
Case SyntaxKind.PropertyBlock
Return GetPropertyBlockStartPoint(text, DirectCast(node, PropertyBlockSyntax), part)
Case SyntaxKind.PropertyStatement
Return GetPropertyStatementStartPoint(text, DirectCast(node, PropertyStatementSyntax), part)
Case SyntaxKind.EventBlock
Return GetEventBlockStartPoint(text, options, DirectCast(node, EventBlockSyntax), part)
Case SyntaxKind.EventStatement
Return GetEventStatementStartPoint(text, DirectCast(node, EventStatementSyntax), part)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return GetDelegateStatementStartPoint(text, DirectCast(node, DelegateStatementSyntax), part)
Case SyntaxKind.NamespaceBlock
Return GetNamespaceBlockStartPoint(text, options, DirectCast(node, NamespaceBlockSyntax), part)
Case SyntaxKind.NamespaceStatement
Return GetNamespaceBlockStartPoint(text, options, DirectCast(node.Parent, NamespaceBlockSyntax), part)
Case SyntaxKind.ModifiedIdentifier
Return GetVariableStartPoint(text, DirectCast(node, ModifiedIdentifierSyntax), part)
Case SyntaxKind.EnumMemberDeclaration
Return GetVariableStartPoint(text, DirectCast(node, EnumMemberDeclarationSyntax), part)
Case SyntaxKind.Parameter
Return GetParameterStartPoint(text, DirectCast(node, ParameterSyntax), part)
Case SyntaxKind.Attribute
Return GetAttributeStartPoint(text, DirectCast(node, AttributeSyntax), part)
Case SyntaxKind.SimpleArgument,
SyntaxKind.OmittedArgument
Return GetAttributeArgumentStartPoint(text, DirectCast(node, ArgumentSyntax), part)
Case SyntaxKind.SimpleImportsClause
Return GetImportsStatementStartPoint(text, DirectCast(node.Parent, ImportsStatementSyntax), part)
Case SyntaxKind.OptionStatement
Return GetOptionStatementStartPoint(text, DirectCast(node, OptionStatementSyntax), part)
Case SyntaxKind.InheritsStatement
Return GetInheritsStatementStartPoint(text, DirectCast(node, InheritsStatementSyntax), part)
Case SyntaxKind.ImplementsStatement
Return GetImplementsStatementStartPoint(text, DirectCast(node, ImplementsStatementSyntax), part)
Case Else
Debug.Fail(String.Format("Unsupported node kind: {0}", CType(node.Kind, SyntaxKind)))
Throw New NotSupportedException()
End Select
End Function
Protected Overrides Function GetEndPoint(text As SourceText, options As OptionSet, node As SyntaxNode, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Select Case node.Kind
Case SyntaxKind.ClassBlock,
SyntaxKind.InterfaceBlock,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return GetTypeBlockEndPoint(text, DirectCast(node, TypeBlockSyntax), part)
Case SyntaxKind.EnumBlock
Return GetEnumBlockEndPoint(text, DirectCast(node, EnumBlockSyntax), part)
Case SyntaxKind.ClassStatement,
SyntaxKind.InterfaceStatement,
SyntaxKind.ModuleBlock,
SyntaxKind.StructureBlock
Return GetTypeBlockEndPoint(text, DirectCast(node.Parent, TypeBlockSyntax), part)
Case SyntaxKind.EnumStatement
Return GetEnumBlockEndPoint(text, DirectCast(node.Parent, EnumBlockSyntax), part)
Case SyntaxKind.ConstructorBlock,
SyntaxKind.FunctionBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SubBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return GetMethodBlockEndPoint(text, DirectCast(node, MethodBlockBaseSyntax), part)
Case SyntaxKind.SubNewStatement,
SyntaxKind.OperatorStatement,
SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement,
SyntaxKind.AddHandlerStatement,
SyntaxKind.RemoveHandlerStatement,
SyntaxKind.RaiseEventStatement
Return GetMethodBlockEndPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
If TypeOf node.Parent Is MethodBlockBaseSyntax Then
Return GetMethodBlockEndPoint(text, DirectCast(node.Parent, MethodBlockBaseSyntax), part)
Else
Return GetMethodStatementEndPoint(text, DirectCast(node, MethodStatementSyntax), part)
End If
Case SyntaxKind.DeclareFunctionStatement,
SyntaxKind.DeclareSubStatement
Return GetDeclareStatementEndPoint(text, DirectCast(node, DeclareStatementSyntax), part)
Case SyntaxKind.PropertyBlock
Return GetPropertyBlockEndPoint(text, DirectCast(node, PropertyBlockSyntax), part)
Case SyntaxKind.PropertyStatement
Return GetPropertyStatementEndPoint(text, DirectCast(node, PropertyStatementSyntax), part)
Case SyntaxKind.EventBlock
Return GetEventBlockEndPoint(text, DirectCast(node, EventBlockSyntax), part)
Case SyntaxKind.EventStatement
Return GetEventStatementEndPoint(text, DirectCast(node, EventStatementSyntax), part)
Case SyntaxKind.DelegateFunctionStatement,
SyntaxKind.DelegateSubStatement
Return GetDelegateStatementEndPoint(text, DirectCast(node, DelegateStatementSyntax), part)
Case SyntaxKind.NamespaceBlock
Return GetNamespaceBlockEndPoint(text, DirectCast(node, NamespaceBlockSyntax), part)
Case SyntaxKind.NamespaceStatement
Return GetNamespaceBlockEndPoint(text, DirectCast(node.Parent, NamespaceBlockSyntax), part)
Case SyntaxKind.ModifiedIdentifier
Return GetVariableEndPoint(text, DirectCast(node, ModifiedIdentifierSyntax), part)
Case SyntaxKind.EnumMemberDeclaration
Return GetVariableEndPoint(text, DirectCast(node, EnumMemberDeclarationSyntax), part)
Case SyntaxKind.Parameter
Return GetParameterEndPoint(text, DirectCast(node, ParameterSyntax), part)
Case SyntaxKind.Attribute
Return GetAttributeEndPoint(text, DirectCast(node, AttributeSyntax), part)
Case SyntaxKind.SimpleArgument,
SyntaxKind.OmittedArgument
Return GetAttributeArgumentEndPoint(text, DirectCast(node, ArgumentSyntax), part)
Case SyntaxKind.SimpleImportsClause
Return GetImportsStatementEndPoint(text, DirectCast(node.Parent, ImportsStatementSyntax), part)
Case SyntaxKind.OptionStatement
Return GetOptionStatementEndPoint(text, DirectCast(node, OptionStatementSyntax), part)
Case SyntaxKind.InheritsStatement
Return GetInheritsStatementEndPoint(text, DirectCast(node, InheritsStatementSyntax), part)
Case SyntaxKind.ImplementsStatement
Return GetImplementsStatementEndPoint(text, DirectCast(node, ImplementsStatementSyntax), part)
Case Else
Debug.Fail(String.Format("Unsupported node kind: {0}", CType(node.Kind, SyntaxKind)))
Throw New NotImplementedException()
End Select
End Function
Private Function GetAttributesStartPoint(text As SourceText, attributes As SyntaxList(Of AttributeListSyntax), part As EnvDTE.vsCMPart) As VirtualTreePoint?
' VB has a Code Model bug that causes vsCMPartAttributes and vsCMPartAttributesWithDelimiters to return the same value.
' You can see the issue clearly in vb\Language\VsPackage\CodeModelHelpers.cpp, CodeModelLocations::GetAttributeSpecifierListLocation.
' Essentially, the old code tries to do the right thing for vsCMPartAttributes, but then deliberately falls through to the
' vsCMPartAttributesWithDelimiter case, where it overwrites the calculation it just made. Sigh...
If attributes.Count = 0 Then
Return Nothing
End If
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
startPosition = attributes.First().LessThanToken.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Return Nothing
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attributes.First().SyntaxTree, text, startPosition)
End Function
Private Function GetAttributesEndPoint(text As SourceText, attributes As SyntaxList(Of AttributeListSyntax), part As EnvDTE.vsCMPart) As VirtualTreePoint?
' VB has a Code Model bug that causes vsCMPartAttributes and vsCMPartAttributesWithDelimiters to return the same value.
' See GetAttributesStartPoint for the details
If attributes.Count = 0 Then
Return Nothing
End If
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
startPosition = attributes.Last().GreaterThanToken.Span.End
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Return Nothing
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attributes.Last().SyntaxTree, text, startPosition)
End Function
Private Function GetHeaderStartPosition(typeBlock As TypeBlockSyntax) As Integer
If typeBlock.BlockStatement.Modifiers.Count > 0 Then
Return typeBlock.BlockStatement.Modifiers.First().SpanStart
Else
Return typeBlock.BlockStatement.DeclarationKeyword.SpanStart
End If
End Function
Private Function GetHeaderStartPosition(enumBlock As EnumBlockSyntax) As Integer
If enumBlock.EnumStatement.Modifiers.Count > 0 Then
Return enumBlock.EnumStatement.Modifiers.First().SpanStart
Else
Return enumBlock.EnumStatement.EnumKeyword.SpanStart
End If
End Function
Private Function GetTypeBlockStartPoint(text As SourceText, options As OptionSet, typeBlock As TypeBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = typeBlock.BlockStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, typeBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = typeBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = GetHeaderStartPosition(typeBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim statement As StatementSyntax = typeBlock.BlockStatement
While statement IsNot Nothing
Dim [next] = statement.GetNextNonEmptyStatement()
If [next] IsNot Nothing AndAlso
([next].Kind = SyntaxKind.InheritsStatement OrElse
[next].Kind = SyntaxKind.ImplementsStatement) Then
statement = [next]
Continue While
Else
Exit While
End If
End While
Debug.Assert(statement IsNot Nothing)
Dim statementLine = text.Lines.GetLineFromPosition(statement.SpanStart)
' statement points to either the last Inherits/Implements or to the type declaration itself.
Dim nextStatement = statement.GetNextNonEmptyStatement()
Dim nextStatementLine As Nullable(Of TextLine) = If(nextStatement IsNot Nothing, text.Lines.GetLineFromPosition(nextStatement.SpanStart), Nothing)
' If the next statement is on the same line as the current one, set body start
' position to the end of the current statement
If nextStatementLine IsNot Nothing AndAlso nextStatementLine.Value.LineNumber = statementLine.LineNumber Then
startPosition = statement.Span.End
Else
' Otherwise, use the beginning of the next line.
startPosition = text.Lines(statementLine.LineNumber + 1).Start
End If
If part = EnvDTE.vsCMPart.vsCMPartNavigate Then
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), typeBlock.BlockStatement, statementLine.LineNumber + 1)
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(typeBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetTypeBlockEndPoint(text As SourceText, typeBlock As TypeBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = typeBlock.BlockStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, typeBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = typeBlock.BlockStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = typeBlock.Span.End
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = typeBlock.EndBlockStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(typeBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetEnumBlockStartPoint(text As SourceText, options As OptionSet, enumBlock As EnumBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = enumBlock.EnumStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, enumBlock.EnumStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = enumBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = GetHeaderStartPosition(enumBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim statement As StatementSyntax = enumBlock.EnumStatement
Dim statementLine = text.Lines.GetLineFromPosition(statement.SpanStart)
Dim nextStatement = statement.GetNextNonEmptyStatement()
Dim nextStatementLine As Nullable(Of TextLine) = If(nextStatement IsNot Nothing, text.Lines.GetLineFromPosition(nextStatement.SpanStart), Nothing)
' If the next statement is on the same line as the current one, set body start
' position to the end of the current statement
If nextStatementLine IsNot Nothing AndAlso nextStatementLine.Value.LineNumber = statementLine.LineNumber Then
startPosition = statement.Span.End
Else
' Otherwise, use the beginning of the next line.
startPosition = text.Lines(statementLine.LineNumber + 1).Start
End If
If part = EnvDTE.vsCMPart.vsCMPartNavigate Then
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), enumBlock.EnumStatement, statementLine.LineNumber + 1)
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetEnumBlockEndPoint(text As SourceText, enumBlock As EnumBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = enumBlock.EnumStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, enumBlock.EnumStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = enumBlock.EnumStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = enumBlock.Span.End
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = enumBlock.EndEnumStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetMethodBlockStartPoint(text As SourceText, options As OptionSet, methodBlock As MethodBlockBaseSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
Select Case methodBlock.BlockStatement.Kind
Case SyntaxKind.SubNewStatement
startPosition = DirectCast(methodBlock.BlockStatement, SubNewStatementSyntax).NewKeyword.SpanStart
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
startPosition = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier.SpanStart
Case SyntaxKind.OperatorStatement
startPosition = DirectCast(methodBlock.BlockStatement, OperatorStatementSyntax).OperatorToken.SpanStart
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
' For properties accessors, use the name of property block
Dim propertyBlock = methodBlock.FirstAncestorOrSelf(Of PropertyBlockSyntax)()
If propertyBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetPropertyBlockStartPoint(text, propertyBlock, part)
Case SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' For event accessors, use the name of event block
Dim eventBlock = methodBlock.FirstAncestorOrSelf(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetEventBlockStartPoint(text, options, eventBlock, part)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, methodBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = methodBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = NavigationPointHelpers.GetHeaderStartPosition(methodBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), methodBlock)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim startLine = text.Lines.GetLineFromPosition(NavigationPointHelpers.GetHeaderStartPosition(methodBlock))
startPosition = text.Lines(startLine.LineNumber + 1).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetDeclareStatementStartPoint(text As SourceText, declareStatement As DeclareStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = declareStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, declareStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If declareStatement.AttributeLists.Count > 0 Then
startPosition = declareStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = declareStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = declareStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(declareStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetDeclareStatementEndPoint(text As SourceText, declareStatement As DeclareStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = declareStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, declareStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = declareStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(declareStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetMethodStatementStartPoint(text As SourceText, methodStatement As MethodStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = methodStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, methodStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If methodStatement.AttributeLists.Count > 0 Then
startPosition = methodStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = methodStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = methodStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetMethodBlockEndPoint(text As SourceText, methodBlock As MethodBlockBaseSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
Select Case methodBlock.BlockStatement.Kind
Case SyntaxKind.SubNewStatement
startPosition = DirectCast(methodBlock.BlockStatement, SubNewStatementSyntax).NewKeyword.Span.End
Case SyntaxKind.FunctionStatement,
SyntaxKind.SubStatement
startPosition = DirectCast(methodBlock.BlockStatement, MethodStatementSyntax).Identifier.Span.End
Case SyntaxKind.OperatorStatement
startPosition = DirectCast(methodBlock.BlockStatement, OperatorStatementSyntax).OperatorToken.Span.End
Case SyntaxKind.GetAccessorStatement,
SyntaxKind.SetAccessorStatement
' For properties accessors, use the name of property block
Dim propertyBlock = methodBlock.FirstAncestorOrSelf(Of PropertyBlockSyntax)()
If propertyBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetPropertyBlockEndPoint(text, propertyBlock, part)
Case SyntaxKind.AddHandlerAccessorStatement,
SyntaxKind.RemoveHandlerAccessorStatement,
SyntaxKind.RaiseEventAccessorStatement
' For event accessors, use the name of event block
Dim eventBlock = methodBlock.FirstAncestorOrSelf(Of EventBlockSyntax)()
If eventBlock Is Nothing Then
Throw Exceptions.ThrowEFail()
End If
Return GetEventBlockEndPoint(text, eventBlock, part)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, methodBlock.BlockStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = methodBlock.BlockStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = methodBlock.Span.End
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = methodBlock.EndBlockStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetMethodStatementEndPoint(text As SourceText, methodStatement As MethodStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = methodStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, methodStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = methodStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(methodStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetPropertyBlockStartPoint(text As SourceText, propertyBlock As PropertyBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Return GetPropertyStatementStartPoint(text, propertyBlock.PropertyStatement, part)
End Function
Private Function GetPropertyStatementStartPoint(text As SourceText, propertyStatement As PropertyStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = propertyStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, propertyStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
If propertyStatement.AttributeLists.Count > 0 Then
startPosition = propertyStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = propertyStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = propertyStatement.SpanStart
Case EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim beginLine = text.Lines.IndexOf(propertyStatement.Span.End)
Dim lineNumber = beginLine + 1
startPosition = text.Lines(lineNumber).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(propertyStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetPropertyBlockEndPoint(text As SourceText, propertyBlock As PropertyBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Return GetPropertyStatementEndPoint(text, propertyBlock.PropertyStatement, part)
End Function
Private Function GetPropertyStatementEndPoint(text As SourceText, propertyStatement As PropertyStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = propertyStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, propertyStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = propertyStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = If(propertyStatement.IsParentKind(SyntaxKind.PropertyBlock),
DirectCast(propertyStatement.Parent, PropertyBlockSyntax).EndPropertyStatement.Span.End,
propertyStatement.Span.End)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
EnvDTE.vsCMPart.vsCMPartNavigate
' Oddity of VB code model: this only happens if it isn't an auto-property. Otherwise, the start of the file is returned.
startPosition = If(propertyStatement.IsParentKind(SyntaxKind.PropertyBlock),
DirectCast(propertyStatement.Parent, PropertyBlockSyntax).EndPropertyStatement.SpanStart,
0)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(propertyStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetEventBlockStartPoint(text As SourceText, options As OptionSet, eventBlock As EventBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = eventBlock.EventStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, eventBlock.EventStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = eventBlock.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = NavigationPointHelpers.GetHeaderStartPosition(eventBlock)
Case EnvDTE.vsCMPart.vsCMPartNavigate
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), eventBlock)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim startLine = text.Lines.GetLineFromPosition(NavigationPointHelpers.GetHeaderStartPosition(eventBlock))
startPosition = text.Lines(startLine.LineNumber + 1).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(eventBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetEventStatementStartPoint(text As SourceText, eventStatement As EventStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = eventStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, eventStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If eventStatement.AttributeLists.Count > 0 Then
startPosition = eventStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = eventStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = eventStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(eventStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetEventBlockEndPoint(text As SourceText, eventBlock As EventBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Return GetEventStatementEndPoint(text, eventBlock.EventStatement, part)
End Function
Private Function GetEventStatementEndPoint(text As SourceText, eventStatement As EventStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = eventStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, eventStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes
startPosition = eventStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = If(eventStatement.IsParentKind(SyntaxKind.EventBlock),
DirectCast(eventStatement.Parent, EventBlockSyntax).EndEventStatement.Span.End,
eventStatement.Span.End)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
EnvDTE.vsCMPart.vsCMPartNavigate
startPosition = If(eventStatement.IsParentKind(SyntaxKind.EventBlock),
DirectCast(eventStatement.Parent, EventBlockSyntax).EndEventStatement.SpanStart,
eventStatement.Span.End)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(eventStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetDelegateStatementStartPoint(text As SourceText, delegateStatement As DelegateStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = delegateStatement.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, delegateStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If delegateStatement.AttributeLists.Count > 0 Then
startPosition = delegateStatement.AttributeLists.Last().GetLastToken().GetNextToken().SpanStart
Else
startPosition = delegateStatement.SpanStart
End If
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = delegateStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(delegateStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetDelegateStatementEndPoint(text As SourceText, delegateStatement As DelegateStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = delegateStatement.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, delegateStatement.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = delegateStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(delegateStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetTrailingColonTrivia(statement As StatementSyntax) As SyntaxTrivia?
If Not statement.HasTrailingTrivia Then
Return Nothing
End If
Return statement _
.GetTrailingTrivia() _
.FirstOrNull(Function(t) t.Kind = SyntaxKind.ColonTrivia)
End Function
Private Function GetNamespaceBlockStartPoint(text As SourceText, options As OptionSet, namespaceBlock As NamespaceBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = namespaceBlock.NamespaceStatement.Name.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole
startPosition = namespaceBlock.NamespaceStatement.SpanStart
Case EnvDTE.vsCMPart.vsCMPartNavigate
Dim beginStatement = namespaceBlock.NamespaceStatement
Dim beginLine = text.Lines.IndexOf(beginStatement.SpanStart)
Dim lineNumber = beginLine + 1
' If the begin statement has trailing colon trivia, we assume the body starts at the colon.
Dim colonTrivia = GetTrailingColonTrivia(beginStatement)
If colonTrivia IsNot Nothing Then
lineNumber = text.Lines.IndexOf(colonTrivia.Value.SpanStart)
End If
Return NavigationPointHelpers.GetNavigationPoint(text, GetTabSize(options), namespaceBlock.NamespaceStatement, lineNumber)
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
Dim beginStatement = namespaceBlock.NamespaceStatement
Dim endStatement = namespaceBlock.EndNamespaceStatement
' Handle case where begin statement has trailing colon trivia, e.g. Namespace N : End Namespace
Dim colonTrivia = GetTrailingColonTrivia(beginStatement)
If colonTrivia IsNot Nothing Then
startPosition = colonTrivia.Value.SpanStart
Exit Select
End If
Dim beginLine = text.Lines.IndexOf(beginStatement.SpanStart)
Dim lineNumber = beginLine + 1
startPosition = text.Lines(lineNumber).Start
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(namespaceBlock.SyntaxTree, text, startPosition)
End Function
Private Function GetNamespaceBlockEndPoint(text As SourceText, namespaceBlock As NamespaceBlockSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = namespaceBlock.NamespaceStatement.Name.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader
endPosition = namespaceBlock.NamespaceStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole
endPosition = namespaceBlock.EndNamespaceStatement.Span.End
Case EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter,
EnvDTE.vsCMPart.vsCMPartNavigate
endPosition = namespaceBlock.EndNamespaceStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(namespaceBlock.SyntaxTree, text, endPosition)
End Function
Private Function GetVariableStartPoint(text As SourceText, variable As ModifiedIdentifierSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim fieldDeclaration = variable.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
Debug.Assert(fieldDeclaration IsNot Nothing)
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = variable.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, fieldDeclaration.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = fieldDeclaration.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If fieldDeclaration.Modifiers.Count > 0 Then
startPosition = fieldDeclaration.Modifiers.First().SpanStart
Else
startPosition = fieldDeclaration.Declarators.First().SpanStart
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(variable.SyntaxTree, text, startPosition)
End Function
Private Function GetVariableStartPoint(text As SourceText, enumMember As EnumMemberDeclarationSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = enumMember.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, enumMember.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = enumMember.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = enumMember.Identifier.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumMember.SyntaxTree, text, startPosition)
End Function
Private Function GetVariableEndPoint(text As SourceText, variable As ModifiedIdentifierSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim fieldDeclaration = variable.FirstAncestorOrSelf(Of FieldDeclarationSyntax)()
Debug.Assert(fieldDeclaration IsNot Nothing)
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = variable.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, fieldDeclaration.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = fieldDeclaration.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(variable.SyntaxTree, text, endPosition)
End Function
Private Function GetVariableEndPoint(text As SourceText, enumMember As EnumMemberDeclarationSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = enumMember.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, enumMember.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = enumMember.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(enumMember.SyntaxTree, text, endPosition)
End Function
Private Function GetParameterStartPoint(text As SourceText, parameter As ParameterSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = parameter.Identifier.SpanStart
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesStartPoint(text, parameter.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes
startPosition = parameter.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
If parameter.Modifiers.Any() Then
startPosition = parameter.Modifiers.First().SpanStart
Else
startPosition = parameter.Identifier.SpanStart
End If
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(parameter.SyntaxTree, text, startPosition)
End Function
Private Function GetParameterEndPoint(text As SourceText, parameter As ParameterSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = parameter.Identifier.Span.End
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return GetAttributesEndPoint(text, parameter.AttributeLists, part)
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = parameter.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(parameter.SyntaxTree, text, endPosition)
End Function
Private Function GetImportsStatementStartPoint(text As SourceText, importsStatement As ImportsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = importsStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(importsStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetImportsStatementEndPoint(text As SourceText, importsStatement As ImportsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = importsStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(importsStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetOptionStatementStartPoint(text As SourceText, optionStatement As OptionStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = optionStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(optionStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetOptionStatementEndPoint(text As SourceText, optionStatement As OptionStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = optionStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(optionStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetInheritsStatementStartPoint(text As SourceText, inheritsStatement As InheritsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = inheritsStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(inheritsStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetInheritsStatementEndPoint(text As SourceText, inheritsStatement As InheritsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = inheritsStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(inheritsStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetImplementsStatementStartPoint(text As SourceText, implementsStatement As ImplementsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = implementsStatement.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(implementsStatement.SyntaxTree, text, startPosition)
End Function
Private Function GetImplementsStatementEndPoint(text As SourceText, implementsStatement As ImplementsStatementSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = implementsStatement.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(implementsStatement.SyntaxTree, text, endPosition)
End Function
Private Function GetAttributeStartPoint(text As SourceText, attribute As AttributeSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
startPosition = attribute.Name.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = attribute.SpanStart
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attribute.SyntaxTree, text, startPosition)
End Function
Private Function GetAttributeEndPoint(text As SourceText, attribute As AttributeSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
endPosition = attribute.Name.Span.End
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = attribute.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(attribute.SyntaxTree, text, endPosition)
End Function
Private Function GetAttributeArgumentStartPoint(text As SourceText, argument As ArgumentSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim startPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
If Not argument.IsNamed Then
Return Nothing
End If
startPosition = DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.SpanStart
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
startPosition = If(argument.Kind = SyntaxKind.OmittedArgument,
argument.SpanStart - 1,
argument.SpanStart)
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(argument.SyntaxTree, text, startPosition)
End Function
Private Function GetAttributeArgumentEndPoint(text As SourceText, argument As ArgumentSyntax, part As EnvDTE.vsCMPart) As VirtualTreePoint?
Dim endPosition As Integer
Select Case part
Case EnvDTE.vsCMPart.vsCMPartAttributes,
EnvDTE.vsCMPart.vsCMPartAttributesWithDelimiter
Return Nothing
Case EnvDTE.vsCMPart.vsCMPartName
If Not argument.IsNamed Then
Return Nothing
End If
endPosition = DirectCast(argument, SimpleArgumentSyntax).NameColonEquals.Name.Span.End
Case EnvDTE.vsCMPart.vsCMPartHeaderWithAttributes,
EnvDTE.vsCMPart.vsCMPartHeader,
EnvDTE.vsCMPart.vsCMPartWholeWithAttributes,
EnvDTE.vsCMPart.vsCMPartWhole,
EnvDTE.vsCMPart.vsCMPartNavigate,
EnvDTE.vsCMPart.vsCMPartName,
EnvDTE.vsCMPart.vsCMPartBody,
EnvDTE.vsCMPart.vsCMPartBodyWithDelimiter
endPosition = argument.Span.End
Case Else
Throw Exceptions.ThrowEFail()
End Select
Return New VirtualTreePoint(argument.SyntaxTree, text, endPosition)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Operations/OperationMapBuilder.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis
{
internal static class OperationMapBuilder
{
/// <summary>
/// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node.
/// If there is a SyntaxNode with more than one explicit IOperation, this will throw.
/// </summary>
internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary)
{
Debug.Assert(dictionary.Count == 0);
Walker.Instance.Visit(root, dictionary);
}
private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>>
{
internal static readonly Walker Instance = new Walker();
public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument)
{
RecordOperation(operation, argument);
return base.DefaultVisit(operation, argument);
}
public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument)
{
// In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive,
// so we don't need to maintain a stack, just iterate through every level.
while (true)
{
RecordOperation(operation, argument);
Visit(operation.RightOperand, argument);
if (operation.LeftOperand is IBinaryOperation nested)
{
operation = nested;
}
else
{
Visit(operation.LeftOperand, argument);
break;
}
}
return null;
}
internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument)
{
// OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation.
// we need to deal with it here, however, so delegate to DefaultVisit.
return DefaultVisit(operation, argument);
}
private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument)
{
if (!operation.IsImplicit)
{
// IOperation invariant is that all there is at most 1 non-implicit node per syntax node.
argument.Add(operation.Syntax, operation);
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Operations;
namespace Microsoft.CodeAnalysis
{
internal static class OperationMapBuilder
{
/// <summary>
/// Populates a empty dictionary of SyntaxNode->IOperation, where every key corresponds to an explicit IOperation node.
/// If there is a SyntaxNode with more than one explicit IOperation, this will throw.
/// </summary>
internal static void AddToMap(IOperation root, Dictionary<SyntaxNode, IOperation> dictionary)
{
Debug.Assert(dictionary.Count == 0);
Walker.Instance.Visit(root, dictionary);
}
private sealed class Walker : OperationWalker<Dictionary<SyntaxNode, IOperation>>
{
internal static readonly Walker Instance = new Walker();
public override object? DefaultVisit(IOperation operation, Dictionary<SyntaxNode, IOperation> argument)
{
RecordOperation(operation, argument);
return base.DefaultVisit(operation, argument);
}
public override object? VisitBinaryOperator([DisallowNull] IBinaryOperation? operation, Dictionary<SyntaxNode, IOperation> argument)
{
// In order to handle very large nested operators, we implement manual iteration here. Our operations are not order sensitive,
// so we don't need to maintain a stack, just iterate through every level.
while (true)
{
RecordOperation(operation, argument);
Visit(operation.RightOperand, argument);
if (operation.LeftOperand is IBinaryOperation nested)
{
operation = nested;
}
else
{
Visit(operation.LeftOperand, argument);
break;
}
}
return null;
}
internal override object? VisitNoneOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument)
{
// OperationWalker skips these nodes by default, to avoid having public consumers deal with NoneOperation.
// we need to deal with it here, however, so delegate to DefaultVisit.
return DefaultVisit(operation, argument);
}
private static void RecordOperation(IOperation operation, Dictionary<SyntaxNode, IOperation> argument)
{
if (!operation.IsImplicit)
{
// IOperation invariant is that all there is at most 1 non-implicit node per syntax node.
argument.Add(operation.Syntax, operation);
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Binder/LocalInProgressBinder.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This binder keeps track of the local variable (if any) that is currently being evaluated
/// so that it can be passed into the next call to LocalSymbol.GetConstantValue (and
/// its callers).
/// </summary>
internal sealed class LocalInProgressBinder : Binder
{
private readonly LocalSymbol _inProgress;
internal LocalInProgressBinder(LocalSymbol inProgress, Binder next)
: base(next)
{
_inProgress = inProgress;
}
internal override LocalSymbol LocalInProgress
{
get
{
return _inProgress;
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This binder keeps track of the local variable (if any) that is currently being evaluated
/// so that it can be passed into the next call to LocalSymbol.GetConstantValue (and
/// its callers).
/// </summary>
internal sealed class LocalInProgressBinder : Binder
{
private readonly LocalSymbol _inProgress;
internal LocalInProgressBinder(LocalSymbol inProgress, Binder next)
: base(next)
{
_inProgress = inProgress;
}
internal override LocalSymbol LocalInProgress
{
get
{
return _inProgress;
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements
<Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)>
Public NotInheritable Class SplitIntoNestedIfStatementsTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicSplitIntoNestedIfStatementsCodeRefactoringProvider()
End Function
<Theory>
<InlineData("a [||]andalso b")>
<InlineData("a an[||]dalso b")>
<InlineData("a andalso[||] b")>
<InlineData("a [|andalso|] b")>
Public Async Function SplitOnAndAlsoOperatorSpans(condition As String) As Task
Await TestInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
if {condition} then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
end if
end if
end sub
end class")
End Function
<Theory>
<InlineData("a [|and|]also b")>
<InlineData("a[| andalso|] b")>
<InlineData("a[||] andalso b")>
Public Async Function NotSplitOnAndAlsoOperatorSpans(condition As String) As Task
Await TestMissingInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
if {condition} then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnIfKeyword() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[||]if a andalso b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnOrElseOperator() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]orelse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnBitwiseAndOperator() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]and b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnAndAlsoOperatorOutsideIfStatement() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
dim v = a [||]andalso b
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnAndAlsoOperatorInIfStatementBody() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a andalso b then
a [||]andalso b
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnSingleLineIf() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then System.Console.WriteLine()
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithChainedAndAlsoExpression1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a [||]andalso b andalso c andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a then
if b andalso c andalso d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithChainedAndAlsoExpression2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b [||]andalso c andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b then
if c andalso d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithChainedAndAlsoExpression3() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b andalso c [||]andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b andalso c then
if d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitInsideParentheses1() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if (a [||]andalso b) andalso c andalso d then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitInsideParentheses2() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b andalso (c [||]andalso d) then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitInsideParentheses3() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if (a andalso b [||]andalso c andalso d) then
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithOtherExpressionInsideParentheses1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a [||]andalso (b andalso c) andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a then
if (b andalso c) andalso d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithOtherExpressionInsideParentheses2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso (b andalso c) [||]andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso (b andalso c) then
if d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitWithMixedOrElseExpression1() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a [||]andalso b orelse c then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitWithMixedOrElseExpression2() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a orelse b [||]andalso c then
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedOrElseExpressionInsideParentheses1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a [||]andalso (b orelse c) then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
if (b orelse c) then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedOrElseExpressionInsideParentheses2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if (a orelse b) [||]andalso c then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if (a orelse b) then
if c then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedEqualsExpression1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a [||]andalso b = c then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
if b = c then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedEqualsExpression2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a = b [||]andalso c then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a = b then
if c then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine(a andalso b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine(a andalso b)
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithNestedIfStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
if true
end if
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
if true
end if
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithElseStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine()
else
System.Console.WriteLine(a andalso b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine()
else
System.Console.WriteLine(a andalso b)
end if
else
System.Console.WriteLine(a andalso b)
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithElseNestedIfStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine()
else
if true
end if
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine()
else
if true
end if
end if
else
if true
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithElseIfElse() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine()
elseif a then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine()
elseif a then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
elseif a then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitAsPartOfElseIfElse() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a [||]andalso b then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a then
if b then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
else
System.Console.WriteLine(b)
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitAsPartOfElseIfElseIf() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a [||]andalso b then
System.Console.WriteLine(a)
elseif a orelse b
System.Console.WriteLine(b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a then
if b then
System.Console.WriteLine(a)
elseif a orelse b
System.Console.WriteLine(b)
end if
elseif a orelse b
System.Console.WriteLine(b)
end if
end sub
end class")
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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements
<Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)>
Public NotInheritable Class SplitIntoNestedIfStatementsTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicSplitIntoNestedIfStatementsCodeRefactoringProvider()
End Function
<Theory>
<InlineData("a [||]andalso b")>
<InlineData("a an[||]dalso b")>
<InlineData("a andalso[||] b")>
<InlineData("a [|andalso|] b")>
Public Async Function SplitOnAndAlsoOperatorSpans(condition As String) As Task
Await TestInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
if {condition} then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
end if
end if
end sub
end class")
End Function
<Theory>
<InlineData("a [|and|]also b")>
<InlineData("a[| andalso|] b")>
<InlineData("a[||] andalso b")>
Public Async Function NotSplitOnAndAlsoOperatorSpans(condition As String) As Task
Await TestMissingInRegularAndScriptAsync(
$"class C
sub M(a as boolean, b as boolean)
if {condition} then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnIfKeyword() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
[||]if a andalso b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnOrElseOperator() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]orelse b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnBitwiseAndOperator() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]and b then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnAndAlsoOperatorOutsideIfStatement() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
dim v = a [||]andalso b
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnAndAlsoOperatorInIfStatementBody() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a andalso b then
a [||]andalso b
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitOnSingleLineIf() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then System.Console.WriteLine()
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithChainedAndAlsoExpression1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a [||]andalso b andalso c andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a then
if b andalso c andalso d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithChainedAndAlsoExpression2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b [||]andalso c andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b then
if c andalso d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithChainedAndAlsoExpression3() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b andalso c [||]andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b andalso c then
if d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitInsideParentheses1() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if (a [||]andalso b) andalso c andalso d then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitInsideParentheses2() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso b andalso (c [||]andalso d) then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitInsideParentheses3() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if (a andalso b [||]andalso c andalso d) then
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithOtherExpressionInsideParentheses1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a [||]andalso (b andalso c) andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a then
if (b andalso c) andalso d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithOtherExpressionInsideParentheses2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso (b andalso c) [||]andalso d then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean, d as boolean)
if a andalso (b andalso c) then
if d then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitWithMixedOrElseExpression1() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a [||]andalso b orelse c then
end if
end sub
end class")
End Function
<Fact>
Public Async Function NotSplitWithMixedOrElseExpression2() As Task
Await TestMissingInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a orelse b [||]andalso c then
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedOrElseExpressionInsideParentheses1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a [||]andalso (b orelse c) then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
if (b orelse c) then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedOrElseExpressionInsideParentheses2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if (a orelse b) [||]andalso c then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if (a orelse b) then
if c then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedEqualsExpression1() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a [||]andalso b = c then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a then
if b = c then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithMixedEqualsExpression2() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a = b [||]andalso c then
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean, c as boolean)
if a = b then
if c then
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine(a andalso b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine(a andalso b)
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithNestedIfStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
if true
end if
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
if true
end if
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithElseStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine()
else
System.Console.WriteLine(a andalso b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine()
else
System.Console.WriteLine(a andalso b)
end if
else
System.Console.WriteLine(a andalso b)
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithElseNestedIfStatement() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine()
else
if true
end if
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine()
else
if true
end if
end if
else
if true
end if
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitWithElseIfElse() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if a [||]andalso b then
System.Console.WriteLine()
elseif a then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if a then
if b then
System.Console.WriteLine()
elseif a then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
elseif a then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitAsPartOfElseIfElse() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a [||]andalso b then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a then
if b then
System.Console.WriteLine(a)
else
System.Console.WriteLine(b)
end if
else
System.Console.WriteLine(b)
end if
end sub
end class")
End Function
<Fact>
Public Async Function SplitAsPartOfElseIfElseIf() As Task
Await TestInRegularAndScriptAsync(
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a [||]andalso b then
System.Console.WriteLine(a)
elseif a orelse b
System.Console.WriteLine(b)
end if
end sub
end class",
"class C
sub M(a as boolean, b as boolean)
if true then
System.Console.WriteLine()
elseif a then
if b then
System.Console.WriteLine(a)
elseif a orelse b
System.Console.WriteLine(b)
end if
elseif a orelse b
System.Console.WriteLine(b)
end if
end sub
end class")
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/AsyncMethodHighlighterTests.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.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class AsyncMethodHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(AsyncAwaitHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
{|Cursor:[|async|]|} Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
{|Cursor:[|async|]|} Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = [|await|] AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = [|await|] resultTask;
result = [|await|] lambda();
}
}");
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class AsyncMethodHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(AsyncAwaitHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
{|Cursor:[|async|]|} Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = await AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = await resultTask;
result = await lambda();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_1()
{
await TestAsync(
@"using System;
using System.Threading.Tasks;
class AsyncExample
{
async Task<int> AsyncMethod()
{
int hours = 24;
return hours;
}
{|Cursor:[|async|]|} Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await AsyncMethod();
};
int result = [|await|] AsyncMethod();
Task<int> resultTask = AsyncMethod();
result = [|await|] resultTask;
result = [|await|] lambda();
}
}");
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/FindSymbols/SymbolFinder_Declarations_CustomQueries.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.FindSymbols
{
// Logic related to finding declarations with a completely custom predicate goes here.
// Completely custom predicates can not be optimized in any way as there is no way to
// tell what the predicate will return true for.
//
// Also, because we have no control over these predicates, we cannot remote these queries
// over to the OOP process.
public static partial class SymbolFinder
{
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, Func<string, bool> predicate, CancellationToken cancellationToken = default)
=> FindSourceDeclarationsAsync(solution, predicate, SymbolFilter.All, cancellationToken);
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.CreateCustom(predicate);
var declarations = await FindSourceDeclarationsWithCustomQueryAsync(
solution, query, filter, cancellationToken).ConfigureAwait(false);
return declarations;
}
internal static async Task<ImmutableArray<ISymbol>> FindSourceDeclarationsWithCustomQueryAsync(
Solution solution, SearchQuery query, SymbolFilter filter, CancellationToken cancellationToken)
{
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
if (query.Name != null && string.IsNullOrWhiteSpace(query.Name))
{
return ImmutableArray<ISymbol>.Empty;
}
using (Logger.LogBlock(FunctionId.SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync, cancellationToken))
{
var result = ArrayBuilder<ISymbol>.GetInstance();
foreach (var projectId in solution.ProjectIds)
{
var project = solution.GetProject(projectId);
var symbols = await FindSourceDeclarationsWithCustomQueryAsync(project, query, filter, cancellationToken).ConfigureAwait(false);
result.AddRange(symbols);
}
return result.ToImmutableAndFree();
}
}
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, Func<string, bool> predicate, CancellationToken cancellationToken = default)
=> FindSourceDeclarationsAsync(project, predicate, SymbolFilter.All, cancellationToken);
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.CreateCustom(predicate);
var declarations = await FindSourceDeclarationsWithCustomQueryAsync(
project, query, filter, cancellationToken).ConfigureAwait(false);
return declarations;
}
internal static async Task<ImmutableArray<ISymbol>> FindSourceDeclarationsWithCustomQueryAsync(
Project project, SearchQuery query, SymbolFilter filter, CancellationToken cancellationToken)
{
if (project == null)
{
throw new ArgumentNullException(nameof(project));
}
if (query.Name != null && string.IsNullOrWhiteSpace(query.Name))
{
return ImmutableArray<ISymbol>.Empty;
}
using (Logger.LogBlock(FunctionId.SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync, cancellationToken))
{
if (await project.ContainsSymbolsWithNameAsync(query.GetPredicate(), filter, cancellationToken).ConfigureAwait(false))
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var unfiltered = compilation.GetSymbolsWithName(query.GetPredicate(), filter, cancellationToken)
.ToImmutableArray();
return DeclarationFinder.FilterByCriteria(unfiltered, filter);
}
}
return ImmutableArray<ISymbol>.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.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.FindSymbols
{
// Logic related to finding declarations with a completely custom predicate goes here.
// Completely custom predicates can not be optimized in any way as there is no way to
// tell what the predicate will return true for.
//
// Also, because we have no control over these predicates, we cannot remote these queries
// over to the OOP process.
public static partial class SymbolFinder
{
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, Func<string, bool> predicate, CancellationToken cancellationToken = default)
=> FindSourceDeclarationsAsync(solution, predicate, SymbolFilter.All, cancellationToken);
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Solution solution, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.CreateCustom(predicate);
var declarations = await FindSourceDeclarationsWithCustomQueryAsync(
solution, query, filter, cancellationToken).ConfigureAwait(false);
return declarations;
}
internal static async Task<ImmutableArray<ISymbol>> FindSourceDeclarationsWithCustomQueryAsync(
Solution solution, SearchQuery query, SymbolFilter filter, CancellationToken cancellationToken)
{
if (solution == null)
{
throw new ArgumentNullException(nameof(solution));
}
if (query.Name != null && string.IsNullOrWhiteSpace(query.Name))
{
return ImmutableArray<ISymbol>.Empty;
}
using (Logger.LogBlock(FunctionId.SymbolFinder_Solution_Predicate_FindSourceDeclarationsAsync, cancellationToken))
{
var result = ArrayBuilder<ISymbol>.GetInstance();
foreach (var projectId in solution.ProjectIds)
{
var project = solution.GetProject(projectId);
var symbols = await FindSourceDeclarationsWithCustomQueryAsync(project, query, filter, cancellationToken).ConfigureAwait(false);
result.AddRange(symbols);
}
return result.ToImmutableAndFree();
}
}
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, Func<string, bool> predicate, CancellationToken cancellationToken = default)
=> FindSourceDeclarationsAsync(project, predicate, SymbolFilter.All, cancellationToken);
/// <summary>
/// Find the symbols for declarations made in source with a matching name.
/// </summary>
public static async Task<IEnumerable<ISymbol>> FindSourceDeclarationsAsync(Project project, Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken = default)
{
using var query = SearchQuery.CreateCustom(predicate);
var declarations = await FindSourceDeclarationsWithCustomQueryAsync(
project, query, filter, cancellationToken).ConfigureAwait(false);
return declarations;
}
internal static async Task<ImmutableArray<ISymbol>> FindSourceDeclarationsWithCustomQueryAsync(
Project project, SearchQuery query, SymbolFilter filter, CancellationToken cancellationToken)
{
if (project == null)
{
throw new ArgumentNullException(nameof(project));
}
if (query.Name != null && string.IsNullOrWhiteSpace(query.Name))
{
return ImmutableArray<ISymbol>.Empty;
}
using (Logger.LogBlock(FunctionId.SymbolFinder_Project_Predicate_FindSourceDeclarationsAsync, cancellationToken))
{
if (await project.ContainsSymbolsWithNameAsync(query.GetPredicate(), filter, cancellationToken).ConfigureAwait(false))
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
var unfiltered = compilation.GetSymbolsWithName(query.GetPredicate(), filter, cancellationToken)
.ToImmutableArray();
return DeclarationFinder.FilterByCriteria(unfiltered, filter);
}
}
return ImmutableArray<ISymbol>.Empty;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Test/EditAndContinue/EmitSolutionUpdateResultsTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
[UseExportProvider]
public class EmitSolutionUpdateResultsTests
{
[Fact]
public async Task GetHotReloadDiagnostics()
{
using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features);
var sourcePath = Path.Combine(TempRoot.Root, "x", "a.cs");
var razorPath = Path.Combine(TempRoot.Root, "a.razor");
var document = workspace.CurrentSolution.
AddProject("proj", "proj", LanguageNames.CSharp).
WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)).
AddDocument(sourcePath, SourceText.From("class C {}", Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, sourcePath));
var solution = document.Project.Solution;
var diagnosticData = ImmutableArray.Create(
new DiagnosticData(
id: "CS0001",
category: "Test",
message: "warning",
enuMessageForBingSearch: "test2 message format",
severity: DiagnosticSeverity.Warning,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 0,
customTags: ImmutableArray.Create("Test2"),
properties: ImmutableDictionary<string, string?>.Empty,
document.Project.Id,
new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), "a.cs", 0, 0, 0, 5, "a.razor", 10, 10, 10, 15),
language: "C#",
title: "title",
description: "description",
helpLink: "http://link"),
new DiagnosticData(
id: "CS0012",
category: "Test",
message: "error",
enuMessageForBingSearch: "test2 message format",
severity: DiagnosticSeverity.Error,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 0,
customTags: ImmutableArray.Create("Test2"),
properties: ImmutableDictionary<string, string?>.Empty,
document.Project.Id,
new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), originalFilePath: sourcePath, 0, 0, 0, 5, mappedFilePath: @"..\a.razor", 10, 10, 10, 15),
language: "C#",
title: "title",
description: "description",
helpLink: "http://link"));
var rudeEdits = ImmutableArray.Create(
(document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Insert, TextSpan.FromBounds(1, 10), 123, new[] { "a" }))),
(document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Delete, TextSpan.FromBounds(1, 10), 123, new[] { "b" }))));
var actual = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, CancellationToken.None);
AssertEx.Equal(new[]
{
$@"Error CS0012: {razorPath} (10,10)-(10,15): error",
$@"Error ENC0021: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Adding_0_will_prevent_the_debug_session_from_continuing, "a")}",
$@"Error ENC0033: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Deleting_0_will_prevent_the_debug_session_from_continuing, "b")}"
}, actual.Select(d => $"{d.Severity} {d.Id}: {d.FilePath} {d.Span.GetDebuggerDisplay()}: {d.Message}"));
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.EditAndContinue;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
[UseExportProvider]
public class EmitSolutionUpdateResultsTests
{
[Fact]
public async Task GetHotReloadDiagnostics()
{
using var workspace = new TestWorkspace(composition: FeaturesTestCompositions.Features);
var sourcePath = Path.Combine(TempRoot.Root, "x", "a.cs");
var razorPath = Path.Combine(TempRoot.Root, "a.razor");
var document = workspace.CurrentSolution.
AddProject("proj", "proj", LanguageNames.CSharp).
WithMetadataReferences(TargetFrameworkUtil.GetReferences(TargetFramework.Standard)).
AddDocument(sourcePath, SourceText.From("class C {}", Encoding.UTF8), filePath: Path.Combine(TempRoot.Root, sourcePath));
var solution = document.Project.Solution;
var diagnosticData = ImmutableArray.Create(
new DiagnosticData(
id: "CS0001",
category: "Test",
message: "warning",
enuMessageForBingSearch: "test2 message format",
severity: DiagnosticSeverity.Warning,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 0,
customTags: ImmutableArray.Create("Test2"),
properties: ImmutableDictionary<string, string?>.Empty,
document.Project.Id,
new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), "a.cs", 0, 0, 0, 5, "a.razor", 10, 10, 10, 15),
language: "C#",
title: "title",
description: "description",
helpLink: "http://link"),
new DiagnosticData(
id: "CS0012",
category: "Test",
message: "error",
enuMessageForBingSearch: "test2 message format",
severity: DiagnosticSeverity.Error,
defaultSeverity: DiagnosticSeverity.Warning,
isEnabledByDefault: true,
warningLevel: 0,
customTags: ImmutableArray.Create("Test2"),
properties: ImmutableDictionary<string, string?>.Empty,
document.Project.Id,
new DiagnosticDataLocation(document.Id, new TextSpan(1, 2), originalFilePath: sourcePath, 0, 0, 0, 5, mappedFilePath: @"..\a.razor", 10, 10, 10, 15),
language: "C#",
title: "title",
description: "description",
helpLink: "http://link"));
var rudeEdits = ImmutableArray.Create(
(document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Insert, TextSpan.FromBounds(1, 10), 123, new[] { "a" }))),
(document.Id, ImmutableArray.Create(new RudeEditDiagnostic(RudeEditKind.Delete, TextSpan.FromBounds(1, 10), 123, new[] { "b" }))));
var actual = await EmitSolutionUpdateResults.GetHotReloadDiagnosticsAsync(solution, diagnosticData, rudeEdits, CancellationToken.None);
AssertEx.Equal(new[]
{
$@"Error CS0012: {razorPath} (10,10)-(10,15): error",
$@"Error ENC0021: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Adding_0_will_prevent_the_debug_session_from_continuing, "a")}",
$@"Error ENC0033: {sourcePath} (0,1)-(0,10): {string.Format(FeaturesResources.Deleting_0_will_prevent_the_debug_session_from_continuing, "b")}"
}, actual.Select(d => $"{d.Severity} {d.Id}: {d.FilePath} {d.Span.GetDebuggerDisplay()}: {d.Message}"));
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/WhereKeywordRecommender.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the "Where" query clause.
''' </summary>
Friend Class WhereKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Where", VBFeaturesResources.Specifies_the_filtering_condition_for_a_range_variable_in_a_query))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the "Where" query clause.
''' </summary>
Friend Class WhereKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Where", VBFeaturesResources.Specifies_the_filtering_condition_for_a_range_variable_in_a_query))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsQueryOperatorContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/EnumConstantHelper.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.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal enum EnumOverflowKind { NoOverflow, OverflowReport, OverflowIgnore }
internal static class EnumConstantHelper
{
/// <summary>
/// Generate a ConstantValue of the same integer type as the argument
/// and offset by the given non-negative amount. Return ConstantValue.Bad
/// if the generated constant would be outside the valid range of the type.
/// </summary>
internal static EnumOverflowKind OffsetValue(ConstantValue constantValue, uint offset, out ConstantValue offsetValue)
{
Debug.Assert(!constantValue.IsBad);
Debug.Assert(offset > 0);
offsetValue = ConstantValue.Bad;
EnumOverflowKind overflowKind;
switch (constantValue.Discriminator)
{
case ConstantValueTypeDiscriminator.SByte:
{
long previous = constantValue.SByteValue;
overflowKind = CheckOverflow(sbyte.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((sbyte)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Byte:
{
ulong previous = constantValue.ByteValue;
overflowKind = CheckOverflow(byte.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((byte)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Int16:
{
long previous = constantValue.Int16Value;
overflowKind = CheckOverflow(short.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((short)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.UInt16:
{
ulong previous = constantValue.UInt16Value;
overflowKind = CheckOverflow(ushort.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((ushort)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Int32:
{
long previous = constantValue.Int32Value;
overflowKind = CheckOverflow(int.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((int)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.UInt32:
{
ulong previous = constantValue.UInt32Value;
overflowKind = CheckOverflow(uint.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((uint)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Int64:
{
long previous = constantValue.Int64Value;
overflowKind = CheckOverflow(long.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((long)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.UInt64:
{
ulong previous = constantValue.UInt64Value;
overflowKind = CheckOverflow(ulong.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((ulong)(previous + offset));
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(constantValue.Discriminator);
}
return overflowKind;
}
private static EnumOverflowKind CheckOverflow(long maxOffset, long previous, uint offset)
{
Debug.Assert(maxOffset >= previous);
return CheckOverflow(unchecked((ulong)(maxOffset - previous)), offset);
}
private static EnumOverflowKind CheckOverflow(ulong maxOffset, ulong previous, uint offset)
{
Debug.Assert(maxOffset >= previous);
return CheckOverflow(maxOffset - previous, offset);
}
private static EnumOverflowKind CheckOverflow(ulong maxOffset, uint offset)
{
return (offset <= maxOffset) ?
EnumOverflowKind.NoOverflow :
(((offset - 1) == maxOffset) ? EnumOverflowKind.OverflowReport : EnumOverflowKind.OverflowIgnore);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal enum EnumOverflowKind { NoOverflow, OverflowReport, OverflowIgnore }
internal static class EnumConstantHelper
{
/// <summary>
/// Generate a ConstantValue of the same integer type as the argument
/// and offset by the given non-negative amount. Return ConstantValue.Bad
/// if the generated constant would be outside the valid range of the type.
/// </summary>
internal static EnumOverflowKind OffsetValue(ConstantValue constantValue, uint offset, out ConstantValue offsetValue)
{
Debug.Assert(!constantValue.IsBad);
Debug.Assert(offset > 0);
offsetValue = ConstantValue.Bad;
EnumOverflowKind overflowKind;
switch (constantValue.Discriminator)
{
case ConstantValueTypeDiscriminator.SByte:
{
long previous = constantValue.SByteValue;
overflowKind = CheckOverflow(sbyte.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((sbyte)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Byte:
{
ulong previous = constantValue.ByteValue;
overflowKind = CheckOverflow(byte.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((byte)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Int16:
{
long previous = constantValue.Int16Value;
overflowKind = CheckOverflow(short.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((short)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.UInt16:
{
ulong previous = constantValue.UInt16Value;
overflowKind = CheckOverflow(ushort.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((ushort)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Int32:
{
long previous = constantValue.Int32Value;
overflowKind = CheckOverflow(int.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((int)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.UInt32:
{
ulong previous = constantValue.UInt32Value;
overflowKind = CheckOverflow(uint.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((uint)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.Int64:
{
long previous = constantValue.Int64Value;
overflowKind = CheckOverflow(long.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((long)(previous + offset));
}
}
break;
case ConstantValueTypeDiscriminator.UInt64:
{
ulong previous = constantValue.UInt64Value;
overflowKind = CheckOverflow(ulong.MaxValue, previous, offset);
if (overflowKind == EnumOverflowKind.NoOverflow)
{
offsetValue = ConstantValue.Create((ulong)(previous + offset));
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(constantValue.Discriminator);
}
return overflowKind;
}
private static EnumOverflowKind CheckOverflow(long maxOffset, long previous, uint offset)
{
Debug.Assert(maxOffset >= previous);
return CheckOverflow(unchecked((ulong)(maxOffset - previous)), offset);
}
private static EnumOverflowKind CheckOverflow(ulong maxOffset, ulong previous, uint offset)
{
Debug.Assert(maxOffset >= previous);
return CheckOverflow(maxOffset - previous, offset);
}
private static EnumOverflowKind CheckOverflow(ulong maxOffset, uint offset)
{
return (offset <= maxOffset) ?
EnumOverflowKind.NoOverflow :
(((offset - 1) == maxOffset) ? EnumOverflowKind.OverflowReport : EnumOverflowKind.OverflowIgnore);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Test/Progression/ImplementsGraphQueryTests.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.Tasks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)>
Public Class ImplementsGraphQueryTests
<WpfFact>
Public Async Function TestClassImplementsInterface1() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
class $$C : System.IDisposable { }
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementsGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Internal" Label="C"/>
<Node Id="(@2 Namespace=System Type=IDisposable)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="IDisposable" Icon="Microsoft.VisualStudio.Interface.Public" Label="IDisposable"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@2 Namespace=System Type=IDisposable)" Category="Implements"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
<Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestMethodImplementsInterfaceMethod1() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
class Goo : IComparable
{
public int $$CompareTo(object obj)
{
throw new NotImplementedException();
}
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementsGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" Label="CompareTo"/>
<Node Id="(@2 Namespace=System Type=IComparable Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" Label="CompareTo"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Target="(@2 Namespace=System Type=IComparable Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="Implements"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
<Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.GraphModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Progression
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Progression
<UseExportProvider, Trait(Traits.Feature, Traits.Features.Progression)>
Public Class ImplementsGraphQueryTests
<WpfFact>
Public Async Function TestClassImplementsInterface1() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
class $$C : System.IDisposable { }
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementsGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=C)" Category="CodeSchema_Class" CodeSchemaProperty_IsInternal="True" CommonLabel="C" Icon="Microsoft.VisualStudio.Class.Internal" Label="C"/>
<Node Id="(@2 Namespace=System Type=IDisposable)" Category="CodeSchema_Interface" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="IDisposable" Icon="Microsoft.VisualStudio.Interface.Public" Label="IDisposable"/>
</Nodes>
<Links>
<Link Source="(@1 Type=C)" Target="(@2 Namespace=System Type=IDisposable)" Category="Implements"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
<Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
<WpfFact>
Public Async Function TestMethodImplementsInterfaceMethod1() As Task
Using testState = ProgressionTestState.Create(
<Workspace>
<Project Language="C#" CommonReferences="true" FilePath="Z:\Project.csproj">
<Document FilePath="Z:\Project.cs">
using System;
class Goo : IComparable
{
public int $$CompareTo(object obj)
{
throw new NotImplementedException();
}
}
</Document>
</Project>
</Workspace>)
Dim inputGraph = Await testState.GetGraphWithMarkedSymbolNodeAsync()
Dim outputContext = Await testState.GetGraphContextAfterQuery(inputGraph, New ImplementsGraphQuery(), GraphContextDirection.Target)
AssertSimplifiedGraphIs(
outputContext.Graph,
<DirectedGraph xmlns="http://schemas.microsoft.com/vs/2009/dgml">
<Nodes>
<Node Id="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" Label="CompareTo"/>
<Node Id="(@2 Namespace=System Type=IComparable Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="CodeSchema_Method" CodeSchemaProperty_IsAbstract="True" CodeSchemaProperty_IsPublic="True" CommonLabel="CompareTo" Icon="Microsoft.VisualStudio.Method.Public" Label="CompareTo"/>
</Nodes>
<Links>
<Link Source="(@1 Type=Goo Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Target="(@2 Namespace=System Type=IComparable Member=(Name=CompareTo OverloadingParameters=[(@2 Namespace=System Type=Object)]))" Category="Implements"/>
</Links>
<IdentifierAliases>
<Alias n="1" Uri="Assembly=file:///Z:/CSharpAssembly1.dll"/>
<Alias n="2" Uri="Assembly=file:///Z:/FxReferenceAssembliesUri"/>
</IdentifierAliases>
</DirectedGraph>)
End Using
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/EditorConfigSettings/Extensions/EnumerableExtensions.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;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions
{
internal static class EnumerableExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var seenKeys = new HashSet<TKey>();
foreach (var element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Extensions
{
internal static class EnumerableExtensions
{
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source, Func<TSource, TKey> keySelector)
{
var seenKeys = new HashSet<TKey>();
foreach (var element in source)
{
if (seenKeys.Add(keySelector(element)))
{
yield return element;
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/SourceCodeKindExtensions.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
internal static partial class SourceCodeKindExtensions
{
internal static SourceCodeKind MapSpecifiedToEffectiveKind(this SourceCodeKind kind)
{
switch (kind)
{
case SourceCodeKind.Script:
#pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete
case SourceCodeKind.Interactive:
#pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete
return SourceCodeKind.Script;
case SourceCodeKind.Regular:
default:
return SourceCodeKind.Regular;
}
}
internal static bool IsValid(this SourceCodeKind value)
{
return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Script;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis
{
internal static partial class SourceCodeKindExtensions
{
internal static SourceCodeKind MapSpecifiedToEffectiveKind(this SourceCodeKind kind)
{
switch (kind)
{
case SourceCodeKind.Script:
#pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete
case SourceCodeKind.Interactive:
#pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete
return SourceCodeKind.Script;
case SourceCodeKind.Regular:
default:
return SourceCodeKind.Regular;
}
}
internal static bool IsValid(this SourceCodeKind value)
{
return value >= SourceCodeKind.Regular && value <= SourceCodeKind.Script;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Syntax/Syntax/ConstantExpressionEvaluatorTests.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Public Class ConstantExpressionEvaluatorTests
Inherits BasicTestBase
<Fact>
Public Sub ConstantValueGetDiscriminatorTest01()
Assert.Equal(ConstantValueTypeDiscriminator.SByte, SpecialType.System_SByte.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Byte, SpecialType.System_Byte.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Int16, SpecialType.System_Int16.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.UInt16, SpecialType.System_UInt16.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Int32, SpecialType.System_Int32.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.UInt32, SpecialType.System_UInt32.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Int64, SpecialType.System_Int64.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.UInt64, SpecialType.System_UInt64.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Char, SpecialType.System_Char.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Boolean, SpecialType.System_Boolean.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Single, SpecialType.System_Single.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Double, SpecialType.System_Double.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Decimal, SpecialType.System_Decimal.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.DateTime, SpecialType.System_DateTime.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.String, SpecialType.System_String.ToConstantValueDiscriminator())
End Sub
End Class
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Public Class ConstantExpressionEvaluatorTests
Inherits BasicTestBase
<Fact>
Public Sub ConstantValueGetDiscriminatorTest01()
Assert.Equal(ConstantValueTypeDiscriminator.SByte, SpecialType.System_SByte.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Byte, SpecialType.System_Byte.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Int16, SpecialType.System_Int16.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.UInt16, SpecialType.System_UInt16.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Int32, SpecialType.System_Int32.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.UInt32, SpecialType.System_UInt32.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Int64, SpecialType.System_Int64.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.UInt64, SpecialType.System_UInt64.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Char, SpecialType.System_Char.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Boolean, SpecialType.System_Boolean.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Single, SpecialType.System_Single.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Double, SpecialType.System_Double.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.Decimal, SpecialType.System_Decimal.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.DateTime, SpecialType.System_DateTime.ToConstantValueDiscriminator())
Assert.Equal(ConstantValueTypeDiscriminator.String, SpecialType.System_String.ToConstantValueDiscriminator())
End Sub
End Class
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/LanguageServer/Protocol/Handler/Completion/CompletionHandler.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Handle a completion request.
/// </summary>
internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?>
{
private readonly ImmutableHashSet<char> _csharpTriggerCharacters;
private readonly ImmutableHashSet<char> _vbTriggerCharacters;
private readonly CompletionListCache _completionListCache;
public string Method => LSP.Methods.TextDocumentCompletionName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public CompletionHandler(
IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders,
CompletionListCache completionListCache)
{
_csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_completionListCache = completionListCache;
}
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument;
public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return null;
}
// C# and VB share the same LSP language server, and thus share the same default trigger characters.
// We need to ensure the trigger character is valid in the document's language. For example, the '{'
// character, while a trigger character in VB, is not a trigger character in C#.
if (request.Context != null &&
request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter &&
!char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) &&
!char.IsLetterOrDigit(triggerCharacter) &&
!IsValidTriggerCharacterForDocument(document, triggerCharacter))
{
return null;
}
var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false);
var completionService = document.GetRequiredLanguageService<CompletionService>();
var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false);
if (completionListResult == null)
{
return null;
}
var (list, isIncomplete, resultId) = completionListResult.Value;
var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true;
var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false;
var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance);
// Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size).
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
// We also check against the CompletionOption for test purposes only.
Contract.ThrowIfNull(context.Solution);
var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>();
var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) ||
completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language);
TextSpan? defaultSpan = null;
LSP.Range? defaultRange = null;
if (returnTextEdits)
{
// We want to compute the document's text just once.
documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// We use the first item in the completion list as our comparison point for span
// and range for optimization when generating the TextEdits later on.
var completionChange = await completionService.GetChangeAsync(
document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false);
// If possible, we want to compute the item's span and range just once.
// Individual items can override this range later.
defaultSpan = completionChange.TextChange.Span;
defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText);
}
var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability();
var completionResolveData = new CompletionResolveData()
{
ResultId = resultId,
};
var stringBuilder = new StringBuilder();
using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems);
foreach (var item in list.Items)
{
var completionItemResolveData = supportsCompletionListData ? null : completionResolveData;
var lspCompletionItem = await CreateLSPCompletionItemAsync(
request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache,
completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText,
defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
lspCompletionItems.Add(lspCompletionItem);
}
var completionList = new LSP.VSCompletionList
{
Items = lspCompletionItems.ToArray(),
SuggestionMode = list.SuggestionModeItem != null,
IsIncomplete = isIncomplete,
};
if (supportsCompletionListData)
{
completionList.Data = completionResolveData;
}
if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability())
{
PromoteCommonCommitCharactersOntoList(completionList);
}
var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList);
return optimizedCompletionList;
// Local functions
bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter)
{
if (document.Project.Language == LanguageNames.CSharp)
{
return _csharpTriggerCharacters.Contains(triggerCharacter);
}
else if (document.Project.Language == LanguageNames.VisualBasic)
{
return _vbTriggerCharacters.Contains(triggerCharacter);
}
// Typescript still calls into this for completion.
// Since we don't know what their trigger characters are, just return true.
return true;
}
static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
if (supportsVSExtensions)
{
var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId());
return vsCompletionItem;
}
else
{
var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
return roslynCompletionItem;
}
}
static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new()
{
// Generate display text
stringBuilder.Append(item.DisplayTextPrefix);
stringBuilder.Append(item.DisplayText);
stringBuilder.Append(item.DisplayTextSuffix);
var completeDisplayText = stringBuilder.ToString();
stringBuilder.Clear();
var completionItem = new TCompletionItem
{
Label = completeDisplayText,
SortText = item.SortText,
FilterText = item.FilterText,
Kind = GetCompletionKind(item.Tags),
Data = completionResolveData,
Preselect = ShouldItemBePreselected(item),
};
// Complex text edits (e.g. override and partial method completions) are always populated in the
// resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases.
if (item.IsComplexTextEdit)
{
// Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet.
// We can enable it for regular C# once LSP is used for local completion.
if (snippetsSupported)
{
completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet;
}
}
// If the feature flag is on, always return a TextEdit.
else if (returnTextEdits)
{
var textEdit = await GenerateTextEdit(
document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
completionItem.TextEdit = textEdit;
}
// If the feature flag is off, return an InsertText.
else
{
completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText;
}
var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions);
if (commitCharacters != null)
{
completionItem.CommitCharacters = commitCharacters;
}
return completionItem;
static async Task<LSP.TextEdit> GenerateTextEdit(
Document document,
CompletionItem item,
CompletionService completionService,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(documentText);
Contract.ThrowIfNull(defaultSpan);
Contract.ThrowIfNull(defaultRange);
var completionChange = await completionService.GetChangeAsync(
document, item, cancellationToken: cancellationToken).ConfigureAwait(false);
var completionChangeSpan = completionChange.TextChange.Span;
var textEdit = new LSP.TextEdit()
{
NewText = completionChange.TextChange.NewText ?? "",
Range = completionChangeSpan == defaultSpan.Value
? defaultRange
: ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText),
};
return textEdit;
}
}
static string[]? GetCommitCharacters(
CompletionItem item,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache,
bool supportsVSExtensions)
{
// VSCode does not have the concept of soft selection, the list is always hard selected.
// In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc
// we create a completion item without any specific commit characters. This means only tab / enter will commit.
// VS supports soft selection, so we only do this for non-VS clients.
if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection)
{
return Array.Empty<string>();
}
var commitCharacterRules = item.Rules.CommitCharacterRules;
// VS will use the default commit characters if no items are specified on the completion item.
// However, other clients like VSCode do not support this behavior so we must specify
// commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987
if (supportsVSExtensions && commitCharacterRules.IsEmpty)
{
return null;
}
if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters))
{
return cachedCommitCharacters;
}
using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters);
commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters);
foreach (var rule in commitCharacterRules)
{
switch (rule.Kind)
{
case CharacterSetModificationKind.Add:
commitCharacters.UnionWith(rule.Characters);
continue;
case CharacterSetModificationKind.Remove:
commitCharacters.ExceptWith(rule.Characters);
continue;
case CharacterSetModificationKind.Replace:
commitCharacters.Clear();
commitCharacters.AddRange(rule.Characters);
break;
}
}
var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray();
currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters);
return lspCommitCharacters;
}
static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList)
{
var commitCharacterReferences = new Dictionary<object, int>();
var mostUsedCount = 0;
string[]? mostUsedCommitCharacters = null;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
var commitCharacters = completionItem.CommitCharacters;
if (commitCharacters == null)
{
continue;
}
commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount);
existingCount++;
if (existingCount > mostUsedCount)
{
// Capture the most used commit character counts so we don't need to re-iterate the array later
mostUsedCommitCharacters = commitCharacters;
mostUsedCount = existingCount;
}
commitCharacterReferences[commitCharacters] = existingCount;
}
Contract.ThrowIfNull(mostUsedCommitCharacters);
// Promoted the most used commit characters onto the list and then remove these from child items.
completionList.CommitCharacters = mostUsedCommitCharacters;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
if (completionItem.CommitCharacters == mostUsedCommitCharacters)
{
completionItem.CommitCharacters = null;
}
}
}
}
private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync(
LSP.CompletionParams request,
SourceText sourceText,
Document document,
OptionSet completionOptions,
CompletionService completionService,
CancellationToken cancellationToken)
{
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false);
var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions;
(CompletionList List, long ResultId)? result;
if (isTriggerForIncompleteCompletions)
{
// We don't have access to the original trigger, but we know the completion list is already present.
// It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger.
var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke);
result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
else
{
// This is a new completion request, clear out the last result Id for incomplete results.
result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
if (result == null)
{
return null;
}
var resultId = result.Value.ResultId;
var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize);
var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document);
return (completionList, isIncomplete, resultId);
}
private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync(
LSP.CompletionParams request,
Document document,
int position,
CompletionTrigger completionTrigger,
OptionSet completionOptions,
CompletionService completionService,
CompletionListCache completionListCache,
CancellationToken cancellationToken)
{
var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
if (completionList == null || completionList.Items.IsEmpty)
{
return null;
}
// Cache the completion list so we can avoid recomputation in the resolve handler
var resultId = completionListCache.UpdateCache(request.TextDocument, completionList);
return (completionList, resultId);
}
private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList(
CompletionList completionList,
int completionListMaxSize,
TextSpan completionListSpan,
CompletionTrigger completionTrigger,
SourceText sourceText,
Document document)
{
var filterText = sourceText.GetSubText(completionListSpan).ToString();
// Use pattern matching to determine which items are most relevant out of the calculated items.
using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder);
var index = 0;
var completionHelper = CompletionHelper.GetHelper(document);
foreach (var item in completionList.Items)
{
if (CompletionHelper.TryCreateMatchResult<CompletionItem?>(
completionHelper,
item,
editorCompletionItem: null,
filterText,
completionTrigger.Kind,
GetFilterReason(completionTrigger),
recentItems: ImmutableArray<string>.Empty,
includeMatchSpans: false,
index,
out var matchResult))
{
matchResultsBuilder.Add(matchResult);
index++;
}
}
// Next, we sort the list based on the pattern matching result.
matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer);
// Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000.
var filteredList = matchResultsBuilder
.Take(completionListMaxSize)
.Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem)))
.Select(matchResult => matchResult.RoslynCompletionItem)
.ToImmutableArray();
var newCompletionList = completionList.WithItems(filteredList);
// Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will
// not generate any more completion items. This means that we should be checking if the matchedResults is larger
// than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion
// when a character is deleted to go from a complete list back to an incomplete list.
// For example, the following scenario.
// User types "So" -> server gives subset of items for "So" with isIncomplete = true
// User types "m" -> server gives entire set of items for "Som" with isIncomplete = false
// User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n"
//
// Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som"
// so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large.
// VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142
var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length;
return (newCompletionList, isIncomplete);
static CompletionFilterReason GetFilterReason(CompletionTrigger trigger)
{
return trigger.Kind switch
{
CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion,
CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion,
_ => CompletionFilterReason.Other,
};
}
}
private static bool ShouldItemBePreselected(CompletionItem completionItem)
{
// An item should be preselcted for LSP when the match priority is preselect and the item is hard selected.
// LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing.
return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection;
}
internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider)
{
if (provider is LSPCompletionProvider lspProvider)
{
return lspProvider.TriggerCharacters;
}
return ImmutableHashSet<char>.Empty;
}
internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken)
{
// Filter out snippets as they are not supported in the LSP client
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740
// Filter out unimported types for now as there are two issues with providing them:
// 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace.
// https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759
// 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request.
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/
// 3. LSP client should support completion filters / expanders
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var completionOptions = documentOptions
.WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude)
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false)
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false);
return completionOptions;
}
private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind))
{
return completionItemKind;
}
}
return LSP.CompletionItemKind.Text;
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly CompletionHandler _completionHandler;
public TestAccessor(CompletionHandler completionHandler)
=> _completionHandler = completionHandler;
public CompletionListCache GetCache()
=> _completionHandler._completionListCache;
}
private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>>
{
public static readonly CommitCharacterArrayComparer Instance = new();
private CommitCharacterArrayComparer()
{
}
public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y)
{
for (var i = 0; i < x.Length; i++)
{
var xKind = x[i].Kind;
var yKind = y[i].Kind;
if (xKind != yKind)
{
return false;
}
var xCharacters = x[i].Characters;
var yCharacters = y[i].Characters;
if (xCharacters.Length != yCharacters.Length)
{
return false;
}
for (var j = 0; j < xCharacters.Length; j++)
{
if (xCharacters[j] != yCharacters[j])
{
return false;
}
}
}
return true;
}
public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj)
{
var combinedHash = Hash.CombineValues(obj);
return combinedHash;
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Experiments;
using Microsoft.CodeAnalysis.LanguageServer.Handler.Completion;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Roslyn.Utilities;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.Handler
{
/// <summary>
/// Handle a completion request.
/// </summary>
internal class CompletionHandler : IRequestHandler<LSP.CompletionParams, LSP.CompletionList?>
{
private readonly ImmutableHashSet<char> _csharpTriggerCharacters;
private readonly ImmutableHashSet<char> _vbTriggerCharacters;
private readonly CompletionListCache _completionListCache;
public string Method => LSP.Methods.TextDocumentCompletionName;
public bool MutatesSolutionState => false;
public bool RequiresLSPSolution => true;
public CompletionHandler(
IEnumerable<Lazy<CompletionProvider, CompletionProviderMetadata>> completionProviders,
CompletionListCache completionListCache)
{
_csharpTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.CSharp).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_vbTriggerCharacters = completionProviders.Where(lz => lz.Metadata.Language == LanguageNames.VisualBasic).SelectMany(
lz => GetTriggerCharacters(lz.Value)).ToImmutableHashSet();
_completionListCache = completionListCache;
}
public LSP.TextDocumentIdentifier? GetTextDocumentIdentifier(LSP.CompletionParams request) => request.TextDocument;
public async Task<LSP.CompletionList?> HandleRequestAsync(LSP.CompletionParams request, RequestContext context, CancellationToken cancellationToken)
{
var document = context.Document;
if (document == null)
{
return null;
}
// C# and VB share the same LSP language server, and thus share the same default trigger characters.
// We need to ensure the trigger character is valid in the document's language. For example, the '{'
// character, while a trigger character in VB, is not a trigger character in C#.
if (request.Context != null &&
request.Context.TriggerKind == LSP.CompletionTriggerKind.TriggerCharacter &&
!char.TryParse(request.Context.TriggerCharacter, out var triggerCharacter) &&
!char.IsLetterOrDigit(triggerCharacter) &&
!IsValidTriggerCharacterForDocument(document, triggerCharacter))
{
return null;
}
var completionOptions = await GetCompletionOptionsAsync(document, cancellationToken).ConfigureAwait(false);
var completionService = document.GetRequiredLanguageService<CompletionService>();
var documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var completionListResult = await GetFilteredCompletionListAsync(request, documentText, document, completionOptions, completionService, cancellationToken).ConfigureAwait(false);
if (completionListResult == null)
{
return null;
}
var (list, isIncomplete, resultId) = completionListResult.Value;
var lspVSClientCapability = context.ClientCapabilities.HasVisualStudioLspCapability() == true;
var snippetsSupported = context.ClientCapabilities.TextDocument?.Completion?.CompletionItem?.SnippetSupport ?? false;
var commitCharactersRuleCache = new Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]>(CommitCharacterArrayComparer.Instance);
// Feature flag to enable the return of TextEdits instead of InsertTexts (will increase payload size).
// Flag is defined in VisualStudio\Core\Def\PackageRegistration.pkgdef.
// We also check against the CompletionOption for test purposes only.
Contract.ThrowIfNull(context.Solution);
var featureFlagService = context.Solution.Workspace.Services.GetRequiredService<IExperimentationService>();
var returnTextEdits = featureFlagService.IsExperimentEnabled(WellKnownExperimentNames.LSPCompletion) ||
completionOptions.GetOption(CompletionOptions.ForceRoslynLSPCompletionExperiment, document.Project.Language);
TextSpan? defaultSpan = null;
LSP.Range? defaultRange = null;
if (returnTextEdits)
{
// We want to compute the document's text just once.
documentText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
// We use the first item in the completion list as our comparison point for span
// and range for optimization when generating the TextEdits later on.
var completionChange = await completionService.GetChangeAsync(
document, list.Items.First(), cancellationToken: cancellationToken).ConfigureAwait(false);
// If possible, we want to compute the item's span and range just once.
// Individual items can override this range later.
defaultSpan = completionChange.TextChange.Span;
defaultRange = ProtocolConversions.TextSpanToRange(defaultSpan.Value, documentText);
}
var supportsCompletionListData = context.ClientCapabilities.HasCompletionListDataCapability();
var completionResolveData = new CompletionResolveData()
{
ResultId = resultId,
};
var stringBuilder = new StringBuilder();
using var _ = ArrayBuilder<LSP.CompletionItem>.GetInstance(out var lspCompletionItems);
foreach (var item in list.Items)
{
var completionItemResolveData = supportsCompletionListData ? null : completionResolveData;
var lspCompletionItem = await CreateLSPCompletionItemAsync(
request, document, item, completionItemResolveData, lspVSClientCapability, commitCharactersRuleCache,
completionService, context.ClientName, returnTextEdits, snippetsSupported, stringBuilder, documentText,
defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
lspCompletionItems.Add(lspCompletionItem);
}
var completionList = new LSP.VSCompletionList
{
Items = lspCompletionItems.ToArray(),
SuggestionMode = list.SuggestionModeItem != null,
IsIncomplete = isIncomplete,
};
if (supportsCompletionListData)
{
completionList.Data = completionResolveData;
}
if (context.ClientCapabilities.HasCompletionListCommitCharactersCapability())
{
PromoteCommonCommitCharactersOntoList(completionList);
}
var optimizedCompletionList = new LSP.OptimizedVSCompletionList(completionList);
return optimizedCompletionList;
// Local functions
bool IsValidTriggerCharacterForDocument(Document document, char triggerCharacter)
{
if (document.Project.Language == LanguageNames.CSharp)
{
return _csharpTriggerCharacters.Contains(triggerCharacter);
}
else if (document.Project.Language == LanguageNames.VisualBasic)
{
return _vbTriggerCharacters.Contains(triggerCharacter);
}
// Typescript still calls into this for completion.
// Since we don't know what their trigger characters are, just return true.
return true;
}
static async Task<LSP.CompletionItem> CreateLSPCompletionItemAsync(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
if (supportsVSExtensions)
{
var vsCompletionItem = await CreateCompletionItemAsync<LSP.VSCompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
vsCompletionItem.Icon = new ImageElement(item.Tags.GetFirstGlyph().GetImageId());
return vsCompletionItem;
}
else
{
var roslynCompletionItem = await CreateCompletionItemAsync<LSP.CompletionItem>(
request, document, item, completionResolveData, supportsVSExtensions, commitCharacterRulesCache,
completionService, clientName, returnTextEdits, snippetsSupported, stringBuilder,
documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
return roslynCompletionItem;
}
}
static async Task<TCompletionItem> CreateCompletionItemAsync<TCompletionItem>(
LSP.CompletionParams request,
Document document,
CompletionItem item,
CompletionResolveData? completionResolveData,
bool supportsVSExtensions,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> commitCharacterRulesCache,
CompletionService completionService,
string? clientName,
bool returnTextEdits,
bool snippetsSupported,
StringBuilder stringBuilder,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken) where TCompletionItem : LSP.CompletionItem, new()
{
// Generate display text
stringBuilder.Append(item.DisplayTextPrefix);
stringBuilder.Append(item.DisplayText);
stringBuilder.Append(item.DisplayTextSuffix);
var completeDisplayText = stringBuilder.ToString();
stringBuilder.Clear();
var completionItem = new TCompletionItem
{
Label = completeDisplayText,
SortText = item.SortText,
FilterText = item.FilterText,
Kind = GetCompletionKind(item.Tags),
Data = completionResolveData,
Preselect = ShouldItemBePreselected(item),
};
// Complex text edits (e.g. override and partial method completions) are always populated in the
// resolve handler, so we leave both TextEdit and InsertText unpopulated in these cases.
if (item.IsComplexTextEdit)
{
// Razor C# is currently the only language client that supports LSP.InsertTextFormat.Snippet.
// We can enable it for regular C# once LSP is used for local completion.
if (snippetsSupported)
{
completionItem.InsertTextFormat = LSP.InsertTextFormat.Snippet;
}
}
// If the feature flag is on, always return a TextEdit.
else if (returnTextEdits)
{
var textEdit = await GenerateTextEdit(
document, item, completionService, documentText, defaultSpan, defaultRange, cancellationToken).ConfigureAwait(false);
completionItem.TextEdit = textEdit;
}
// If the feature flag is off, return an InsertText.
else
{
completionItem.InsertText = item.Properties.ContainsKey("InsertionText") ? item.Properties["InsertionText"] : completeDisplayText;
}
var commitCharacters = GetCommitCharacters(item, commitCharacterRulesCache, supportsVSExtensions);
if (commitCharacters != null)
{
completionItem.CommitCharacters = commitCharacters;
}
return completionItem;
static async Task<LSP.TextEdit> GenerateTextEdit(
Document document,
CompletionItem item,
CompletionService completionService,
SourceText? documentText,
TextSpan? defaultSpan,
LSP.Range? defaultRange,
CancellationToken cancellationToken)
{
Contract.ThrowIfNull(documentText);
Contract.ThrowIfNull(defaultSpan);
Contract.ThrowIfNull(defaultRange);
var completionChange = await completionService.GetChangeAsync(
document, item, cancellationToken: cancellationToken).ConfigureAwait(false);
var completionChangeSpan = completionChange.TextChange.Span;
var textEdit = new LSP.TextEdit()
{
NewText = completionChange.TextChange.NewText ?? "",
Range = completionChangeSpan == defaultSpan.Value
? defaultRange
: ProtocolConversions.TextSpanToRange(completionChangeSpan, documentText),
};
return textEdit;
}
}
static string[]? GetCommitCharacters(
CompletionItem item,
Dictionary<ImmutableArray<CharacterSetModificationRule>, string[]> currentRuleCache,
bool supportsVSExtensions)
{
// VSCode does not have the concept of soft selection, the list is always hard selected.
// In order to emulate soft selection behavior for things like argument completion, regex completion, datetime completion, etc
// we create a completion item without any specific commit characters. This means only tab / enter will commit.
// VS supports soft selection, so we only do this for non-VS clients.
if (!supportsVSExtensions && item.Rules.SelectionBehavior == CompletionItemSelectionBehavior.SoftSelection)
{
return Array.Empty<string>();
}
var commitCharacterRules = item.Rules.CommitCharacterRules;
// VS will use the default commit characters if no items are specified on the completion item.
// However, other clients like VSCode do not support this behavior so we must specify
// commit characters on every completion item - https://github.com/microsoft/vscode/issues/90987
if (supportsVSExtensions && commitCharacterRules.IsEmpty)
{
return null;
}
if (currentRuleCache.TryGetValue(commitCharacterRules, out var cachedCommitCharacters))
{
return cachedCommitCharacters;
}
using var _ = PooledHashSet<char>.GetInstance(out var commitCharacters);
commitCharacters.AddAll(CompletionRules.Default.DefaultCommitCharacters);
foreach (var rule in commitCharacterRules)
{
switch (rule.Kind)
{
case CharacterSetModificationKind.Add:
commitCharacters.UnionWith(rule.Characters);
continue;
case CharacterSetModificationKind.Remove:
commitCharacters.ExceptWith(rule.Characters);
continue;
case CharacterSetModificationKind.Replace:
commitCharacters.Clear();
commitCharacters.AddRange(rule.Characters);
break;
}
}
var lspCommitCharacters = commitCharacters.Select(c => c.ToString()).ToArray();
currentRuleCache.Add(item.Rules.CommitCharacterRules, lspCommitCharacters);
return lspCommitCharacters;
}
static void PromoteCommonCommitCharactersOntoList(LSP.VSCompletionList completionList)
{
var commitCharacterReferences = new Dictionary<object, int>();
var mostUsedCount = 0;
string[]? mostUsedCommitCharacters = null;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
var commitCharacters = completionItem.CommitCharacters;
if (commitCharacters == null)
{
continue;
}
commitCharacterReferences.TryGetValue(commitCharacters, out var existingCount);
existingCount++;
if (existingCount > mostUsedCount)
{
// Capture the most used commit character counts so we don't need to re-iterate the array later
mostUsedCommitCharacters = commitCharacters;
mostUsedCount = existingCount;
}
commitCharacterReferences[commitCharacters] = existingCount;
}
Contract.ThrowIfNull(mostUsedCommitCharacters);
// Promoted the most used commit characters onto the list and then remove these from child items.
completionList.CommitCharacters = mostUsedCommitCharacters;
for (var i = 0; i < completionList.Items.Length; i++)
{
var completionItem = completionList.Items[i];
if (completionItem.CommitCharacters == mostUsedCommitCharacters)
{
completionItem.CommitCharacters = null;
}
}
}
}
private async Task<(CompletionList CompletionList, bool IsIncomplete, long ResultId)?> GetFilteredCompletionListAsync(
LSP.CompletionParams request,
SourceText sourceText,
Document document,
OptionSet completionOptions,
CompletionService completionService,
CancellationToken cancellationToken)
{
var position = await document.GetPositionFromLinePositionAsync(ProtocolConversions.PositionToLinePosition(request.Position), cancellationToken).ConfigureAwait(false);
var completionListSpan = completionService.GetDefaultCompletionListSpan(sourceText, position);
var completionTrigger = await ProtocolConversions.LSPToRoslynCompletionTriggerAsync(request.Context, document, position, cancellationToken).ConfigureAwait(false);
var isTriggerForIncompleteCompletions = request.Context?.TriggerKind == LSP.CompletionTriggerKind.TriggerForIncompleteCompletions;
(CompletionList List, long ResultId)? result;
if (isTriggerForIncompleteCompletions)
{
// We don't have access to the original trigger, but we know the completion list is already present.
// It is safe to recompute with the invoked trigger as we will get all the items and filter down based on the current trigger.
var originalTrigger = new CompletionTrigger(CompletionTriggerKind.Invoke);
result = await CalculateListAsync(request, document, position, originalTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
else
{
// This is a new completion request, clear out the last result Id for incomplete results.
result = await CalculateListAsync(request, document, position, completionTrigger, completionOptions, completionService, _completionListCache, cancellationToken).ConfigureAwait(false);
}
if (result == null)
{
return null;
}
var resultId = result.Value.ResultId;
var completionListMaxSize = completionOptions.GetOption(LspOptions.MaxCompletionListSize);
var (completionList, isIncomplete) = FilterCompletionList(result.Value.List, completionListMaxSize, completionListSpan, completionTrigger, sourceText, document);
return (completionList, isIncomplete, resultId);
}
private static async Task<(CompletionList CompletionList, long ResultId)?> CalculateListAsync(
LSP.CompletionParams request,
Document document,
int position,
CompletionTrigger completionTrigger,
OptionSet completionOptions,
CompletionService completionService,
CompletionListCache completionListCache,
CancellationToken cancellationToken)
{
var completionList = await completionService.GetCompletionsAsync(document, position, completionTrigger, options: completionOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
if (completionList == null || completionList.Items.IsEmpty)
{
return null;
}
// Cache the completion list so we can avoid recomputation in the resolve handler
var resultId = completionListCache.UpdateCache(request.TextDocument, completionList);
return (completionList, resultId);
}
private static (CompletionList CompletionList, bool IsIncomplete) FilterCompletionList(
CompletionList completionList,
int completionListMaxSize,
TextSpan completionListSpan,
CompletionTrigger completionTrigger,
SourceText sourceText,
Document document)
{
var filterText = sourceText.GetSubText(completionListSpan).ToString();
// Use pattern matching to determine which items are most relevant out of the calculated items.
using var _ = ArrayBuilder<MatchResult<CompletionItem?>>.GetInstance(out var matchResultsBuilder);
var index = 0;
var completionHelper = CompletionHelper.GetHelper(document);
foreach (var item in completionList.Items)
{
if (CompletionHelper.TryCreateMatchResult<CompletionItem?>(
completionHelper,
item,
editorCompletionItem: null,
filterText,
completionTrigger.Kind,
GetFilterReason(completionTrigger),
recentItems: ImmutableArray<string>.Empty,
includeMatchSpans: false,
index,
out var matchResult))
{
matchResultsBuilder.Add(matchResult);
index++;
}
}
// Next, we sort the list based on the pattern matching result.
matchResultsBuilder.Sort(MatchResult<CompletionItem?>.SortingComparer);
// Finally, truncate the list to 1000 items plus any preselected items that occur after the first 1000.
var filteredList = matchResultsBuilder
.Take(completionListMaxSize)
.Concat(matchResultsBuilder.Skip(completionListMaxSize).Where(match => ShouldItemBePreselected(match.RoslynCompletionItem)))
.Select(matchResult => matchResult.RoslynCompletionItem)
.ToImmutableArray();
var newCompletionList = completionList.WithItems(filteredList);
// Per the LSP spec, the completion list should be marked with isIncomplete = false when further insertions will
// not generate any more completion items. This means that we should be checking if the matchedResults is larger
// than the filteredList. However, the VS client has a bug where they do not properly re-trigger completion
// when a character is deleted to go from a complete list back to an incomplete list.
// For example, the following scenario.
// User types "So" -> server gives subset of items for "So" with isIncomplete = true
// User types "m" -> server gives entire set of items for "Som" with isIncomplete = false
// User deletes "m" -> client has to remember that "So" results were incomplete and re-request if the user types something else, like "n"
//
// Currently the VS client does not remember to re-request, so the completion list only ever shows items from "Som"
// so we always set the isIncomplete flag to true when the original list size (computed when no filter text was typed) is too large.
// VS bug here - https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1335142
var isIncomplete = completionList.Items.Length > newCompletionList.Items.Length;
return (newCompletionList, isIncomplete);
static CompletionFilterReason GetFilterReason(CompletionTrigger trigger)
{
return trigger.Kind switch
{
CompletionTriggerKind.Insertion => CompletionFilterReason.Insertion,
CompletionTriggerKind.Deletion => CompletionFilterReason.Deletion,
_ => CompletionFilterReason.Other,
};
}
}
private static bool ShouldItemBePreselected(CompletionItem completionItem)
{
// An item should be preselcted for LSP when the match priority is preselect and the item is hard selected.
// LSP does not support soft preselection, so we do not preselect in that scenario to avoid interfering with typing.
return completionItem.Rules.MatchPriority == MatchPriority.Preselect && completionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection;
}
internal static ImmutableHashSet<char> GetTriggerCharacters(CompletionProvider provider)
{
if (provider is LSPCompletionProvider lspProvider)
{
return lspProvider.TriggerCharacters;
}
return ImmutableHashSet<char>.Empty;
}
internal static async Task<OptionSet> GetCompletionOptionsAsync(Document document, CancellationToken cancellationToken)
{
// Filter out snippets as they are not supported in the LSP client
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1139740
// Filter out unimported types for now as there are two issues with providing them:
// 1. LSP client does not currently provide a way to provide detail text on the completion item to show the namespace.
// https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1076759
// 2. We need to figure out how to provide the text edits along with the completion item or provide them in the resolve request.
// https://devdiv.visualstudio.com/DevDiv/_workitems/edit/985860/
// 3. LSP client should support completion filters / expanders
var documentOptions = await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false);
var completionOptions = documentOptions
.WithChangedOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude)
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, false)
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, false);
return completionOptions;
}
private static LSP.CompletionItemKind GetCompletionKind(ImmutableArray<string> tags)
{
foreach (var tag in tags)
{
if (ProtocolConversions.RoslynTagToCompletionItemKind.TryGetValue(tag, out var completionItemKind))
{
return completionItemKind;
}
}
return LSP.CompletionItemKind.Text;
}
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly CompletionHandler _completionHandler;
public TestAccessor(CompletionHandler completionHandler)
=> _completionHandler = completionHandler;
public CompletionListCache GetCache()
=> _completionHandler._completionListCache;
}
private class CommitCharacterArrayComparer : IEqualityComparer<ImmutableArray<CharacterSetModificationRule>>
{
public static readonly CommitCharacterArrayComparer Instance = new();
private CommitCharacterArrayComparer()
{
}
public bool Equals([AllowNull] ImmutableArray<CharacterSetModificationRule> x, [AllowNull] ImmutableArray<CharacterSetModificationRule> y)
{
for (var i = 0; i < x.Length; i++)
{
var xKind = x[i].Kind;
var yKind = y[i].Kind;
if (xKind != yKind)
{
return false;
}
var xCharacters = x[i].Characters;
var yCharacters = y[i].Characters;
if (xCharacters.Length != yCharacters.Length)
{
return false;
}
for (var j = 0; j < xCharacters.Length; j++)
{
if (xCharacters[j] != yCharacters[j])
{
return false;
}
}
}
return true;
}
public int GetHashCode([DisallowNull] ImmutableArray<CharacterSetModificationRule> obj)
{
var combinedHash = Hash.CombineValues(obj);
return combinedHash;
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Semantic/Semantics/ImplicitlyTypedLocalsTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class ImplicitlyTypedLocalTests : CompilingTestBase
{
[Fact]
public void ConstVarField1()
{
var compilation = CreateCompilation(@"
class var {}
class C
{
const var a = null;
}
");
var fieldA = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
var typeVar = compilation.GlobalNamespace.GetMember<TypeSymbol>("var");
Assert.Equal(typeVar, fieldA.Type);
}
[Fact]
public void ConstVarField2()
{
var compilation = CreateCompilation(@"
using var = System.Int32;
class C
{
const var a = 123;
}
");
var fieldA = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
Assert.Equal(SpecialType.System_Int32, fieldA.Type.SpecialType);
}
[Fact]
public void ImplicitlyTypedVariableAssignedArrayInitializer()
{
string text = @"
var array = { 1, 2 };
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (2,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer
// var array = { 1, 2 };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "array = { 1, 2 }"));
}
[Fact]
public void ImplicitlyTypedVariableCircularReferenceViaMemberAccess()
{
string text = @"
class Program
{
static void Main(string[] args)
{
var x = y.Goo(x);
var y = x.Goo(y);
}
}";
CreateCompilation(text).VerifyDiagnostics(
// (6,23): error CS0841: Cannot use local variable 'x' before it is declared
// var x = y.Goo(x);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 23),
// (6,17): error CS0841: Cannot use local variable 'y' before it is declared
// var x = y.Goo(x);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(6, 17),
// (7,23): error CS0841: Cannot use local variable 'y' before it is declared
// var y = x.Goo(y);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 23)
);
}
[WorkItem(545612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545612")]
[Fact]
public void VarTypeConflictsWithAlias()
{
string alias = @"using var = var;";
string text = @"
class var { }
class B
{
static void Main()
{
var a = 1;
System.Console.WriteLine(a);
}
}
";
// If there's no alias to conflict with the type var, then compilation fails
// because 1 cannot be converted to var.
CreateCompilation(text).VerifyDiagnostics(
// (8,17): error CS0029: Cannot implicitly convert type 'int' to 'var'
// var a = 1;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "var"));
// However, once the alias is introduced, the local becomes implicitly typed
// and everything works.
var verifier = CompileAndVerify(alias + text, expectedOutput: "1");
verifier.VerifyIL("B.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ret
}
");
}
[Fact]
public void VarBeforeCSharp3()
{
var source = @"
class C
{
void M()
{
var v = 1;
System.Console.WriteLine(v);
}
}
class D
{
class var
{
public static implicit operator var(int x) { return null; }
}
void M()
{
var v = 1;
System.Console.WriteLine(v);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3)).VerifyDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp2)).VerifyDiagnostics(
// (6,9): error CS8023: Feature 'implicitly typed local variable' is not available in C# 2. Please use language version 3 or greater.
// var v = 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion2, "var").WithArguments("implicitly typed local variable", "3"));
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class ImplicitlyTypedLocalTests : CompilingTestBase
{
[Fact]
public void ConstVarField1()
{
var compilation = CreateCompilation(@"
class var {}
class C
{
const var a = null;
}
");
var fieldA = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
var typeVar = compilation.GlobalNamespace.GetMember<TypeSymbol>("var");
Assert.Equal(typeVar, fieldA.Type);
}
[Fact]
public void ConstVarField2()
{
var compilation = CreateCompilation(@"
using var = System.Int32;
class C
{
const var a = 123;
}
");
var fieldA = compilation.GlobalNamespace.GetMember<TypeSymbol>("C").GetMember<FieldSymbol>("a");
Assert.Equal(SpecialType.System_Int32, fieldA.Type.SpecialType);
}
[Fact]
public void ImplicitlyTypedVariableAssignedArrayInitializer()
{
string text = @"
var array = { 1, 2 };
";
CreateCompilationWithMscorlib45(text, parseOptions: TestOptions.Script).VerifyDiagnostics(
// (2,5): error CS0820: Cannot initialize an implicitly-typed variable with an array initializer
// var array = { 1, 2 };
Diagnostic(ErrorCode.ERR_ImplicitlyTypedVariableAssignedArrayInitializer, "array = { 1, 2 }"));
}
[Fact]
public void ImplicitlyTypedVariableCircularReferenceViaMemberAccess()
{
string text = @"
class Program
{
static void Main(string[] args)
{
var x = y.Goo(x);
var y = x.Goo(y);
}
}";
CreateCompilation(text).VerifyDiagnostics(
// (6,23): error CS0841: Cannot use local variable 'x' before it is declared
// var x = y.Goo(x);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(6, 23),
// (6,17): error CS0841: Cannot use local variable 'y' before it is declared
// var x = y.Goo(x);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(6, 17),
// (7,23): error CS0841: Cannot use local variable 'y' before it is declared
// var y = x.Goo(y);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "y").WithArguments("y").WithLocation(7, 23)
);
}
[WorkItem(545612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545612")]
[Fact]
public void VarTypeConflictsWithAlias()
{
string alias = @"using var = var;";
string text = @"
class var { }
class B
{
static void Main()
{
var a = 1;
System.Console.WriteLine(a);
}
}
";
// If there's no alias to conflict with the type var, then compilation fails
// because 1 cannot be converted to var.
CreateCompilation(text).VerifyDiagnostics(
// (8,17): error CS0029: Cannot implicitly convert type 'int' to 'var'
// var a = 1;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "var"));
// However, once the alias is introduced, the local becomes implicitly typed
// and everything works.
var verifier = CompileAndVerify(alias + text, expectedOutput: "1");
verifier.VerifyIL("B.Main", @"
{
// Code size 7 (0x7)
.maxstack 1
IL_0000: ldc.i4.1
IL_0001: call ""void System.Console.WriteLine(int)""
IL_0006: ret
}
");
}
[Fact]
public void VarBeforeCSharp3()
{
var source = @"
class C
{
void M()
{
var v = 1;
System.Console.WriteLine(v);
}
}
class D
{
class var
{
public static implicit operator var(int x) { return null; }
}
void M()
{
var v = 1;
System.Console.WriteLine(v);
}
}
";
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp3)).VerifyDiagnostics();
CreateCompilation(source, parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp2)).VerifyDiagnostics(
// (6,9): error CS8023: Feature 'implicitly typed local variable' is not available in C# 2. Please use language version 3 or greater.
// var v = 1;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion2, "var").WithArguments("implicitly typed local variable", "3"));
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/CodeAnalysisTest/MetadataReferences/MetadataReferencePropertiesTests.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 Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: 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.Collections.Immutable;
using System.Linq;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests
{
public class MetadataReferencePropertiesTests
{
[Fact]
public void Constructor()
{
var m = new MetadataReferenceProperties();
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases: ImmutableArray.Create("\\/[.'\":_)??\t\n*#$@^%*&)", "goo"), embedInteropTypes: true);
AssertEx.Equal(new[] { "\\/[.'\":_)??\t\n*#$@^%*&)", "goo" }, m.Aliases);
Assert.True(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Assembly, m.Kind);
m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.True(m.Aliases.IsEmpty);
Assert.False(m.EmbedInteropTypes);
Assert.Equal(MetadataImageKind.Module, m.Kind);
Assert.Equal(MetadataReferenceProperties.Module, new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray<string>.Empty, false));
Assert.Equal(MetadataReferenceProperties.Assembly, new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, false));
}
[Fact]
public void Constructor_Errors()
{
Assert.Throws<ArgumentOutOfRangeException>(() => new MetadataReferenceProperties((MetadataImageKind)byte.MaxValue));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, embedInteropTypes: true));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("")));
Assert.Throws<ArgumentException>(() => new MetadataReferenceProperties(MetadataImageKind.Module, ImmutableArray.Create("x\0x")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(ImmutableArray.Create("blah")));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithAliases(new[] { "blah" }));
Assert.Throws<ArgumentException>(() => MetadataReferenceProperties.Module.WithEmbedInteropTypes(true));
}
[Fact]
public void WithXxx()
{
var a = new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true);
Assert.Equal(a.WithAliases(null), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray<string>.Empty, embedInteropTypes: true));
Assert.Equal(a.WithAliases(ImmutableArray<string>.Empty), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new string[0]), new MetadataReferenceProperties(MetadataImageKind.Assembly, default(ImmutableArray<string>), embedInteropTypes: true));
Assert.Equal(a.WithAliases(new[] { "goo", "aaa" }), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("goo", "aaa"), embedInteropTypes: true));
Assert.Equal(a.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: false));
Assert.Equal(a.WithRecursiveAliases(true), new MetadataReferenceProperties(MetadataImageKind.Assembly, ImmutableArray.Create("a"), embedInteropTypes: true, hasRecursiveAliases: true));
var m = new MetadataReferenceProperties(MetadataImageKind.Module);
Assert.Equal(m.WithAliases(default(ImmutableArray<string>)), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
Assert.Equal(m.WithEmbedInteropTypes(false), new MetadataReferenceProperties(MetadataImageKind.Module, default(ImmutableArray<string>), embedInteropTypes: false));
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Classification/Classifier.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
public static class Classifier
{
public static async Task<IEnumerable<ClassifiedSpan>> GetClassifiedSpansAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken = default)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return GetClassifiedSpans(semanticModel, textSpan, document.Project.Solution.Workspace, cancellationToken);
}
/// <summary>
/// Returns classified spans in ascending <see cref="ClassifiedSpan"/> order.
/// <see cref="ClassifiedSpan"/>s may have the same <see cref="ClassifiedSpan.TextSpan"/>. This occurs when there are multiple
/// <see cref="ClassifiedSpan.ClassificationType"/>s for the same region of code. For example, a reference to a static method
/// will have two spans, one that designates it as a method, and one that designates it as static.
/// <see cref="ClassifiedSpan"/>s may also have overlapping <see cref="ClassifiedSpan.TextSpan"/>s. This occurs when there are
/// strings containing regex and/or escape characters.
/// </summary>
public static IEnumerable<ClassifiedSpan> GetClassifiedSpans(
SemanticModel semanticModel,
TextSpan textSpan,
Workspace workspace,
CancellationToken cancellationToken = default)
{
var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxClassificationService>();
var syntaxClassifiers = service.GetDefaultSyntaxClassifiers();
var extensionManager = workspace.Services.GetRequiredService<IExtensionManager>();
var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(syntaxClassifiers, c => c.SyntaxNodeTypes);
var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(syntaxClassifiers, c => c.SyntaxTokenKinds);
using var _1 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var syntacticClassifications);
using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var semanticClassifications);
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
service.AddSyntacticClassifications(root, textSpan, syntacticClassifications, cancellationToken);
service.AddSemanticClassifications(semanticModel, textSpan, workspace, getNodeClassifiers, getTokenClassifiers, semanticClassifications, cancellationToken);
var allClassifications = new List<ClassifiedSpan>(semanticClassifications.Where(s => s.TextSpan.OverlapsWith(textSpan)));
var semanticSet = semanticClassifications.Select(s => s.TextSpan).ToSet();
allClassifications.AddRange(syntacticClassifications.Where(
s => s.TextSpan.OverlapsWith(textSpan) && !semanticSet.Contains(s.TextSpan)));
allClassifications.Sort((s1, s2) => s1.TextSpan.Start - s2.TextSpan.Start);
return allClassifications;
}
internal static async Task<ImmutableArray<SymbolDisplayPart>> GetClassifiedSymbolDisplayPartsAsync(
SemanticModel semanticModel, TextSpan textSpan, Workspace workspace,
CancellationToken cancellationToken = default)
{
var classifiedSpans = GetClassifiedSpans(semanticModel, textSpan, workspace, cancellationToken);
var sourceText = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return ConvertClassificationsToParts(sourceText, textSpan.Start, classifiedSpans);
}
internal static ImmutableArray<SymbolDisplayPart> ConvertClassificationsToParts(
SourceText sourceText, int startPosition, IEnumerable<ClassifiedSpan> classifiedSpans)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
foreach (var span in classifiedSpans)
{
// If there is space between this span and the last one, then add a space.
if (startPosition < span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, sourceText.ToString(span.TextSpan)));
startPosition = span.TextSpan.End;
}
}
return parts.ToImmutableAndFree();
}
private static IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
private static SymbolDisplayPartKind? GetClassificationKind(string type)
=> type switch
{
ClassificationTypeNames.Identifier => SymbolDisplayPartKind.Text,
ClassificationTypeNames.Keyword => SymbolDisplayPartKind.Keyword,
ClassificationTypeNames.NumericLiteral => SymbolDisplayPartKind.NumericLiteral,
ClassificationTypeNames.StringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.WhiteSpace => SymbolDisplayPartKind.Space,
ClassificationTypeNames.Operator => SymbolDisplayPartKind.Operator,
ClassificationTypeNames.Punctuation => SymbolDisplayPartKind.Punctuation,
ClassificationTypeNames.ClassName => SymbolDisplayPartKind.ClassName,
ClassificationTypeNames.RecordClassName => SymbolDisplayPartKind.RecordClassName,
ClassificationTypeNames.StructName => SymbolDisplayPartKind.StructName,
ClassificationTypeNames.InterfaceName => SymbolDisplayPartKind.InterfaceName,
ClassificationTypeNames.DelegateName => SymbolDisplayPartKind.DelegateName,
ClassificationTypeNames.EnumName => SymbolDisplayPartKind.EnumName,
ClassificationTypeNames.TypeParameterName => SymbolDisplayPartKind.TypeParameterName,
ClassificationTypeNames.ModuleName => SymbolDisplayPartKind.ModuleName,
ClassificationTypeNames.VerbatimStringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.FieldName => SymbolDisplayPartKind.FieldName,
ClassificationTypeNames.EnumMemberName => SymbolDisplayPartKind.EnumMemberName,
ClassificationTypeNames.ConstantName => SymbolDisplayPartKind.ConstantName,
ClassificationTypeNames.LocalName => SymbolDisplayPartKind.LocalName,
ClassificationTypeNames.ParameterName => SymbolDisplayPartKind.ParameterName,
ClassificationTypeNames.ExtensionMethodName => SymbolDisplayPartKind.ExtensionMethodName,
ClassificationTypeNames.MethodName => SymbolDisplayPartKind.MethodName,
ClassificationTypeNames.PropertyName => SymbolDisplayPartKind.PropertyName,
ClassificationTypeNames.LabelName => SymbolDisplayPartKind.LabelName,
ClassificationTypeNames.NamespaceName => SymbolDisplayPartKind.NamespaceName,
ClassificationTypeNames.EventName => SymbolDisplayPartKind.EventName,
_ => null,
};
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Classification
{
public static class Classifier
{
public static async Task<IEnumerable<ClassifiedSpan>> GetClassifiedSpansAsync(
Document document,
TextSpan textSpan,
CancellationToken cancellationToken = default)
{
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return GetClassifiedSpans(semanticModel, textSpan, document.Project.Solution.Workspace, cancellationToken);
}
/// <summary>
/// Returns classified spans in ascending <see cref="ClassifiedSpan"/> order.
/// <see cref="ClassifiedSpan"/>s may have the same <see cref="ClassifiedSpan.TextSpan"/>. This occurs when there are multiple
/// <see cref="ClassifiedSpan.ClassificationType"/>s for the same region of code. For example, a reference to a static method
/// will have two spans, one that designates it as a method, and one that designates it as static.
/// <see cref="ClassifiedSpan"/>s may also have overlapping <see cref="ClassifiedSpan.TextSpan"/>s. This occurs when there are
/// strings containing regex and/or escape characters.
/// </summary>
public static IEnumerable<ClassifiedSpan> GetClassifiedSpans(
SemanticModel semanticModel,
TextSpan textSpan,
Workspace workspace,
CancellationToken cancellationToken = default)
{
var service = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxClassificationService>();
var syntaxClassifiers = service.GetDefaultSyntaxClassifiers();
var extensionManager = workspace.Services.GetRequiredService<IExtensionManager>();
var getNodeClassifiers = extensionManager.CreateNodeExtensionGetter(syntaxClassifiers, c => c.SyntaxNodeTypes);
var getTokenClassifiers = extensionManager.CreateTokenExtensionGetter(syntaxClassifiers, c => c.SyntaxTokenKinds);
using var _1 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var syntacticClassifications);
using var _2 = ArrayBuilder<ClassifiedSpan>.GetInstance(out var semanticClassifications);
var root = semanticModel.SyntaxTree.GetRoot(cancellationToken);
service.AddSyntacticClassifications(root, textSpan, syntacticClassifications, cancellationToken);
service.AddSemanticClassifications(semanticModel, textSpan, workspace, getNodeClassifiers, getTokenClassifiers, semanticClassifications, cancellationToken);
var allClassifications = new List<ClassifiedSpan>(semanticClassifications.Where(s => s.TextSpan.OverlapsWith(textSpan)));
var semanticSet = semanticClassifications.Select(s => s.TextSpan).ToSet();
allClassifications.AddRange(syntacticClassifications.Where(
s => s.TextSpan.OverlapsWith(textSpan) && !semanticSet.Contains(s.TextSpan)));
allClassifications.Sort((s1, s2) => s1.TextSpan.Start - s2.TextSpan.Start);
return allClassifications;
}
internal static async Task<ImmutableArray<SymbolDisplayPart>> GetClassifiedSymbolDisplayPartsAsync(
SemanticModel semanticModel, TextSpan textSpan, Workspace workspace,
CancellationToken cancellationToken = default)
{
var classifiedSpans = GetClassifiedSpans(semanticModel, textSpan, workspace, cancellationToken);
var sourceText = await semanticModel.SyntaxTree.GetTextAsync(cancellationToken).ConfigureAwait(false);
return ConvertClassificationsToParts(sourceText, textSpan.Start, classifiedSpans);
}
internal static ImmutableArray<SymbolDisplayPart> ConvertClassificationsToParts(
SourceText sourceText, int startPosition, IEnumerable<ClassifiedSpan> classifiedSpans)
{
var parts = ArrayBuilder<SymbolDisplayPart>.GetInstance();
foreach (var span in classifiedSpans)
{
// If there is space between this span and the last one, then add a space.
if (startPosition < span.TextSpan.Start)
{
parts.AddRange(Space());
}
var kind = GetClassificationKind(span.ClassificationType);
if (kind != null)
{
parts.Add(new SymbolDisplayPart(kind.Value, null, sourceText.ToString(span.TextSpan)));
startPosition = span.TextSpan.End;
}
}
return parts.ToImmutableAndFree();
}
private static IEnumerable<SymbolDisplayPart> Space(int count = 1)
{
yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count));
}
private static SymbolDisplayPartKind? GetClassificationKind(string type)
=> type switch
{
ClassificationTypeNames.Identifier => SymbolDisplayPartKind.Text,
ClassificationTypeNames.Keyword => SymbolDisplayPartKind.Keyword,
ClassificationTypeNames.NumericLiteral => SymbolDisplayPartKind.NumericLiteral,
ClassificationTypeNames.StringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.WhiteSpace => SymbolDisplayPartKind.Space,
ClassificationTypeNames.Operator => SymbolDisplayPartKind.Operator,
ClassificationTypeNames.Punctuation => SymbolDisplayPartKind.Punctuation,
ClassificationTypeNames.ClassName => SymbolDisplayPartKind.ClassName,
ClassificationTypeNames.RecordClassName => SymbolDisplayPartKind.RecordClassName,
ClassificationTypeNames.StructName => SymbolDisplayPartKind.StructName,
ClassificationTypeNames.InterfaceName => SymbolDisplayPartKind.InterfaceName,
ClassificationTypeNames.DelegateName => SymbolDisplayPartKind.DelegateName,
ClassificationTypeNames.EnumName => SymbolDisplayPartKind.EnumName,
ClassificationTypeNames.TypeParameterName => SymbolDisplayPartKind.TypeParameterName,
ClassificationTypeNames.ModuleName => SymbolDisplayPartKind.ModuleName,
ClassificationTypeNames.VerbatimStringLiteral => SymbolDisplayPartKind.StringLiteral,
ClassificationTypeNames.FieldName => SymbolDisplayPartKind.FieldName,
ClassificationTypeNames.EnumMemberName => SymbolDisplayPartKind.EnumMemberName,
ClassificationTypeNames.ConstantName => SymbolDisplayPartKind.ConstantName,
ClassificationTypeNames.LocalName => SymbolDisplayPartKind.LocalName,
ClassificationTypeNames.ParameterName => SymbolDisplayPartKind.ParameterName,
ClassificationTypeNames.ExtensionMethodName => SymbolDisplayPartKind.ExtensionMethodName,
ClassificationTypeNames.MethodName => SymbolDisplayPartKind.MethodName,
ClassificationTypeNames.PropertyName => SymbolDisplayPartKind.PropertyName,
ClassificationTypeNames.LabelName => SymbolDisplayPartKind.LabelName,
ClassificationTypeNames.NamespaceName => SymbolDisplayPartKind.NamespaceName,
ClassificationTypeNames.EventName => SymbolDisplayPartKind.EventName,
_ => null,
};
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/DocumentHighlighting/CSharpDocumentHighlightsService.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.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.DocumentHighlighting
{
[ExportLanguageService(typeof(IDocumentHighlightsService), LanguageNames.CSharp), Shared]
internal class CSharpDocumentHighlightsService : AbstractDocumentHighlightsService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpDocumentHighlightsService()
{
}
protected override async Task<ImmutableArray<Location>> GetAdditionalReferencesAsync(
Document document, ISymbol symbol, CancellationToken cancellationToken)
{
// The FindRefs engine won't find references through 'var' for performance reasons.
// Also, they are not needed for things like rename/sig change, and the normal find refs
// feature. However, we would like the results to be highlighted to get a good experience
// while editing (especially since highlighting may have been invoked off of 'var' in
// the first place).
//
// So we look for the references through 'var' directly in this file and add them to the
// results found by the engine.
var results = ArrayBuilder<Location>.GetInstance();
if (symbol is INamedTypeSymbol && symbol.Name != "var")
{
var originalSymbol = symbol.OriginalDefinition;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var descendents = root.DescendantNodes();
var semanticModel = (SemanticModel)null;
foreach (var type in descendents.OfType<IdentifierNameSyntax>())
{
cancellationToken.ThrowIfCancellationRequested();
if (type.IsVar)
{
if (semanticModel == null)
{
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
}
var boundSymbol = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol;
boundSymbol = boundSymbol?.OriginalDefinition;
if (originalSymbol.Equals(boundSymbol))
{
results.Add(type.GetLocation());
}
}
}
}
return results.ToImmutableAndFree();
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.CSharp.Syntax;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PooledObjects;
namespace Microsoft.CodeAnalysis.CSharp.DocumentHighlighting
{
[ExportLanguageService(typeof(IDocumentHighlightsService), LanguageNames.CSharp), Shared]
internal class CSharpDocumentHighlightsService : AbstractDocumentHighlightsService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpDocumentHighlightsService()
{
}
protected override async Task<ImmutableArray<Location>> GetAdditionalReferencesAsync(
Document document, ISymbol symbol, CancellationToken cancellationToken)
{
// The FindRefs engine won't find references through 'var' for performance reasons.
// Also, they are not needed for things like rename/sig change, and the normal find refs
// feature. However, we would like the results to be highlighted to get a good experience
// while editing (especially since highlighting may have been invoked off of 'var' in
// the first place).
//
// So we look for the references through 'var' directly in this file and add them to the
// results found by the engine.
var results = ArrayBuilder<Location>.GetInstance();
if (symbol is INamedTypeSymbol && symbol.Name != "var")
{
var originalSymbol = symbol.OriginalDefinition;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var descendents = root.DescendantNodes();
var semanticModel = (SemanticModel)null;
foreach (var type in descendents.OfType<IdentifierNameSyntax>())
{
cancellationToken.ThrowIfCancellationRequested();
if (type.IsVar)
{
if (semanticModel == null)
{
semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
}
var boundSymbol = semanticModel.GetSymbolInfo(type, cancellationToken).Symbol;
boundSymbol = boundSymbol?.OriginalDefinition;
if (originalSymbol.Equals(boundSymbol))
{
results.Add(type.GetLocation());
}
}
}
}
return results.ToImmutableAndFree();
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Symbols/Attributes/AttributeUsageInfo.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 Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal struct AttributeUsageInfo : IEquatable<AttributeUsageInfo>
{
[Flags()]
private enum PackedAttributeUsage
{
None = 0,
Assembly = AttributeTargets.Assembly,
Module = AttributeTargets.Module,
Class = AttributeTargets.Class,
Struct = AttributeTargets.Struct,
Enum = AttributeTargets.Enum,
Constructor = AttributeTargets.Constructor,
Method = AttributeTargets.Method,
Property = AttributeTargets.Property,
Field = AttributeTargets.Field,
Event = AttributeTargets.Event,
Interface = AttributeTargets.Interface,
Parameter = AttributeTargets.Parameter,
Delegate = AttributeTargets.Delegate,
ReturnValue = AttributeTargets.ReturnValue,
GenericParameter = AttributeTargets.GenericParameter,
All = AttributeTargets.All,
// NOTE: VB allows AttributeUsageAttribute with no valid target, i.e. <AttributeUsageAttribute(0)>, and doesn't generate any diagnostics.
// We use PackedAttributeUsage.Initialized field to differentiate between uninitialized AttributeUsageInfo and initialized AttributeUsageInfo with no valid target.
Initialized = GenericParameter << 1,
AllowMultiple = Initialized << 1,
Inherited = AllowMultiple << 1
}
private readonly PackedAttributeUsage _flags;
/// <summary>
/// Default attribute usage for attribute types:
/// (a) Valid targets: AttributeTargets.All
/// (b) AllowMultiple: false
/// (c) Inherited: true
/// </summary>
internal static readonly AttributeUsageInfo Default = new AttributeUsageInfo(validTargets: AttributeTargets.All, allowMultiple: false, inherited: true);
internal static readonly AttributeUsageInfo Null = default(AttributeUsageInfo);
internal AttributeUsageInfo(AttributeTargets validTargets, bool allowMultiple, bool inherited)
{
// NOTE: VB allows AttributeUsageAttribute with no valid target, i.e. <AttributeUsageAttribute(0)>, and doesn't generate any diagnostics.
// We use PackedAttributeUsage.Initialized field to differentiate between uninitialized AttributeUsageInfo and initialized AttributeUsageInfo with no valid targets.
_flags = (PackedAttributeUsage)validTargets | PackedAttributeUsage.Initialized;
if (allowMultiple)
{
_flags |= PackedAttributeUsage.AllowMultiple;
}
if (inherited)
{
_flags |= PackedAttributeUsage.Inherited;
}
}
public bool IsNull
{
get
{
return (_flags & PackedAttributeUsage.Initialized) == 0;
}
}
internal AttributeTargets ValidTargets
{
get
{
return (AttributeTargets)(_flags & PackedAttributeUsage.All);
}
}
internal bool AllowMultiple
{
get
{
return (_flags & PackedAttributeUsage.AllowMultiple) != 0;
}
}
internal bool Inherited
{
get
{
return (_flags & PackedAttributeUsage.Inherited) != 0;
}
}
public static bool operator ==(AttributeUsageInfo left, AttributeUsageInfo right)
{
return left._flags == right._flags;
}
public static bool operator !=(AttributeUsageInfo left, AttributeUsageInfo right)
{
return left._flags != right._flags;
}
public override bool Equals(object? obj)
{
if (obj is AttributeUsageInfo)
{
return this.Equals((AttributeUsageInfo)obj);
}
return false;
}
public bool Equals(AttributeUsageInfo other)
{
return this == other;
}
public override int GetHashCode()
{
return _flags.GetHashCode();
}
internal bool HasValidAttributeTargets
{
get
{
var value = (int)ValidTargets;
return value != 0 && (value & (int)~AttributeTargets.All) == 0;
}
}
internal object GetValidTargetsErrorArgument()
{
var validTargetsInt = (int)ValidTargets;
if (!HasValidAttributeTargets)
{
return string.Empty;
}
var builder = ArrayBuilder<string>.GetInstance();
int flag = 0;
while (validTargetsInt > 0)
{
if ((validTargetsInt & 1) != 0)
{
builder.Add(GetErrorDisplayNameResourceId((AttributeTargets)(1 << flag)));
}
validTargetsInt >>= 1;
flag++;
}
return new ValidTargetsStringLocalizableErrorArgument(builder.ToArrayAndFree());
}
private struct ValidTargetsStringLocalizableErrorArgument : IFormattable
{
private readonly string[]? _targetResourceIds;
internal ValidTargetsStringLocalizableErrorArgument(string[] targetResourceIds)
{
RoslynDebug.Assert(targetResourceIds != null);
_targetResourceIds = targetResourceIds;
}
public override string ToString()
{
return ToString(null, null);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
var builder = PooledStringBuilder.GetInstance();
var culture = formatProvider as System.Globalization.CultureInfo;
if (_targetResourceIds != null)
{
foreach (string id in _targetResourceIds)
{
if (builder.Builder.Length > 0)
{
builder.Builder.Append(", ");
}
builder.Builder.Append(CodeAnalysisResources.ResourceManager.GetString(id, culture));
}
}
var message = builder.Builder.ToString();
builder.Free();
return message;
}
}
private static string GetErrorDisplayNameResourceId(AttributeTargets target)
{
switch (target)
{
case AttributeTargets.Assembly: return nameof(CodeAnalysisResources.Assembly);
case AttributeTargets.Class: return nameof(CodeAnalysisResources.Class1);
case AttributeTargets.Constructor: return nameof(CodeAnalysisResources.Constructor);
case AttributeTargets.Delegate: return nameof(CodeAnalysisResources.Delegate1);
case AttributeTargets.Enum: return nameof(CodeAnalysisResources.Enum1);
case AttributeTargets.Event: return nameof(CodeAnalysisResources.Event1);
case AttributeTargets.Field: return nameof(CodeAnalysisResources.Field);
case AttributeTargets.GenericParameter: return nameof(CodeAnalysisResources.TypeParameter);
case AttributeTargets.Interface: return nameof(CodeAnalysisResources.Interface1);
case AttributeTargets.Method: return nameof(CodeAnalysisResources.Method);
case AttributeTargets.Module: return nameof(CodeAnalysisResources.Module);
case AttributeTargets.Parameter: return nameof(CodeAnalysisResources.Parameter);
case AttributeTargets.Property: return nameof(CodeAnalysisResources.Property);
case AttributeTargets.ReturnValue: return nameof(CodeAnalysisResources.Return1);
case AttributeTargets.Struct: return nameof(CodeAnalysisResources.Struct1);
default:
throw ExceptionUtilities.UnexpectedValue(target);
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
internal struct AttributeUsageInfo : IEquatable<AttributeUsageInfo>
{
[Flags()]
private enum PackedAttributeUsage
{
None = 0,
Assembly = AttributeTargets.Assembly,
Module = AttributeTargets.Module,
Class = AttributeTargets.Class,
Struct = AttributeTargets.Struct,
Enum = AttributeTargets.Enum,
Constructor = AttributeTargets.Constructor,
Method = AttributeTargets.Method,
Property = AttributeTargets.Property,
Field = AttributeTargets.Field,
Event = AttributeTargets.Event,
Interface = AttributeTargets.Interface,
Parameter = AttributeTargets.Parameter,
Delegate = AttributeTargets.Delegate,
ReturnValue = AttributeTargets.ReturnValue,
GenericParameter = AttributeTargets.GenericParameter,
All = AttributeTargets.All,
// NOTE: VB allows AttributeUsageAttribute with no valid target, i.e. <AttributeUsageAttribute(0)>, and doesn't generate any diagnostics.
// We use PackedAttributeUsage.Initialized field to differentiate between uninitialized AttributeUsageInfo and initialized AttributeUsageInfo with no valid target.
Initialized = GenericParameter << 1,
AllowMultiple = Initialized << 1,
Inherited = AllowMultiple << 1
}
private readonly PackedAttributeUsage _flags;
/// <summary>
/// Default attribute usage for attribute types:
/// (a) Valid targets: AttributeTargets.All
/// (b) AllowMultiple: false
/// (c) Inherited: true
/// </summary>
internal static readonly AttributeUsageInfo Default = new AttributeUsageInfo(validTargets: AttributeTargets.All, allowMultiple: false, inherited: true);
internal static readonly AttributeUsageInfo Null = default(AttributeUsageInfo);
internal AttributeUsageInfo(AttributeTargets validTargets, bool allowMultiple, bool inherited)
{
// NOTE: VB allows AttributeUsageAttribute with no valid target, i.e. <AttributeUsageAttribute(0)>, and doesn't generate any diagnostics.
// We use PackedAttributeUsage.Initialized field to differentiate between uninitialized AttributeUsageInfo and initialized AttributeUsageInfo with no valid targets.
_flags = (PackedAttributeUsage)validTargets | PackedAttributeUsage.Initialized;
if (allowMultiple)
{
_flags |= PackedAttributeUsage.AllowMultiple;
}
if (inherited)
{
_flags |= PackedAttributeUsage.Inherited;
}
}
public bool IsNull
{
get
{
return (_flags & PackedAttributeUsage.Initialized) == 0;
}
}
internal AttributeTargets ValidTargets
{
get
{
return (AttributeTargets)(_flags & PackedAttributeUsage.All);
}
}
internal bool AllowMultiple
{
get
{
return (_flags & PackedAttributeUsage.AllowMultiple) != 0;
}
}
internal bool Inherited
{
get
{
return (_flags & PackedAttributeUsage.Inherited) != 0;
}
}
public static bool operator ==(AttributeUsageInfo left, AttributeUsageInfo right)
{
return left._flags == right._flags;
}
public static bool operator !=(AttributeUsageInfo left, AttributeUsageInfo right)
{
return left._flags != right._flags;
}
public override bool Equals(object? obj)
{
if (obj is AttributeUsageInfo)
{
return this.Equals((AttributeUsageInfo)obj);
}
return false;
}
public bool Equals(AttributeUsageInfo other)
{
return this == other;
}
public override int GetHashCode()
{
return _flags.GetHashCode();
}
internal bool HasValidAttributeTargets
{
get
{
var value = (int)ValidTargets;
return value != 0 && (value & (int)~AttributeTargets.All) == 0;
}
}
internal object GetValidTargetsErrorArgument()
{
var validTargetsInt = (int)ValidTargets;
if (!HasValidAttributeTargets)
{
return string.Empty;
}
var builder = ArrayBuilder<string>.GetInstance();
int flag = 0;
while (validTargetsInt > 0)
{
if ((validTargetsInt & 1) != 0)
{
builder.Add(GetErrorDisplayNameResourceId((AttributeTargets)(1 << flag)));
}
validTargetsInt >>= 1;
flag++;
}
return new ValidTargetsStringLocalizableErrorArgument(builder.ToArrayAndFree());
}
private struct ValidTargetsStringLocalizableErrorArgument : IFormattable
{
private readonly string[]? _targetResourceIds;
internal ValidTargetsStringLocalizableErrorArgument(string[] targetResourceIds)
{
RoslynDebug.Assert(targetResourceIds != null);
_targetResourceIds = targetResourceIds;
}
public override string ToString()
{
return ToString(null, null);
}
public string ToString(string? format, IFormatProvider? formatProvider)
{
var builder = PooledStringBuilder.GetInstance();
var culture = formatProvider as System.Globalization.CultureInfo;
if (_targetResourceIds != null)
{
foreach (string id in _targetResourceIds)
{
if (builder.Builder.Length > 0)
{
builder.Builder.Append(", ");
}
builder.Builder.Append(CodeAnalysisResources.ResourceManager.GetString(id, culture));
}
}
var message = builder.Builder.ToString();
builder.Free();
return message;
}
}
private static string GetErrorDisplayNameResourceId(AttributeTargets target)
{
switch (target)
{
case AttributeTargets.Assembly: return nameof(CodeAnalysisResources.Assembly);
case AttributeTargets.Class: return nameof(CodeAnalysisResources.Class1);
case AttributeTargets.Constructor: return nameof(CodeAnalysisResources.Constructor);
case AttributeTargets.Delegate: return nameof(CodeAnalysisResources.Delegate1);
case AttributeTargets.Enum: return nameof(CodeAnalysisResources.Enum1);
case AttributeTargets.Event: return nameof(CodeAnalysisResources.Event1);
case AttributeTargets.Field: return nameof(CodeAnalysisResources.Field);
case AttributeTargets.GenericParameter: return nameof(CodeAnalysisResources.TypeParameter);
case AttributeTargets.Interface: return nameof(CodeAnalysisResources.Interface1);
case AttributeTargets.Method: return nameof(CodeAnalysisResources.Method);
case AttributeTargets.Module: return nameof(CodeAnalysisResources.Module);
case AttributeTargets.Parameter: return nameof(CodeAnalysisResources.Parameter);
case AttributeTargets.Property: return nameof(CodeAnalysisResources.Property);
case AttributeTargets.ReturnValue: return nameof(CodeAnalysisResources.Return1);
case AttributeTargets.Struct: return nameof(CodeAnalysisResources.Struct1);
default:
throw ExceptionUtilities.UnexpectedValue(target);
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/FlowAnalysis/DefiniteAssignment.LocalFunctions.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class DefiniteAssignmentPass
{
internal sealed class LocalFunctionState : AbstractLocalFunctionState
{
public BitVector ReadVars = BitVector.Empty;
public BitVector CapturedMask = BitVector.Null;
public BitVector InvertedCapturedMask = BitVector.Null;
public LocalFunctionState(LocalState stateFromBottom, LocalState stateFromTop)
: base(stateFromBottom, stateFromTop)
{ }
}
protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol)
=> CreateLocalFunctionState();
private LocalFunctionState CreateLocalFunctionState()
=> new LocalFunctionState(
// The bottom state should assume all variables, even new ones, are assigned
new LocalState(BitVector.AllSet(variableBySlot.Count), normalizeToBottom: true),
UnreachableState());
protected override void VisitLocalFunctionUse(
LocalFunctionSymbol localFunc,
LocalFunctionState localFunctionState,
SyntaxNode syntax,
bool isCall)
{
_usedLocalFunctions.Add(localFunc);
// Check variables that were read before being definitely assigned.
var reads = localFunctionState.ReadVars;
// Start at slot 1 (slot 0 just indicates reachability)
for (int slot = 1; slot < reads.Capacity; slot++)
{
if (reads[slot])
{
var symbol = variableBySlot[slot].Symbol;
CheckIfAssignedDuringLocalFunctionReplay(symbol, syntax, slot);
}
}
base.VisitLocalFunctionUse(localFunc, localFunctionState, syntax, isCall);
}
/// <summary>
/// Check that the given variable is definitely assigned when replaying local function
/// reads. If not, produce an error.
/// </summary>
/// <remarks>
/// Specifying the slot manually may be necessary if the symbol is a field,
/// in which case <see cref="LocalDataFlowPass{TLocalState, TLocalFunctionState}.VariableSlot(Symbol, int)"/>
/// will not know which containing slot to look for.
/// </remarks>
private void CheckIfAssignedDuringLocalFunctionReplay(Symbol symbol, SyntaxNode node, int slot)
{
Debug.Assert(!IsConditionalState);
if ((object)symbol != null)
{
NoteRead(symbol);
if (this.State.Reachable)
{
if (slot >= this.State.Assigned.Capacity)
{
Normalize(ref this.State);
}
if (slot > 0 && !this.State.IsAssigned(slot))
{
// Local functions can "call forward" to after a variable has
// been declared but before it has been assigned, so we can never
// consider the declaration location when reporting errors.
ReportUnassignedIfNotCapturedInLocalFunction(symbol, node, slot, skipIfUseBeforeDeclaration: false);
}
}
}
}
private void RecordReadInLocalFunction(int slot)
{
var localFunc = GetNearestLocalFunctionOpt(CurrentSymbol);
Debug.Assert(localFunc != null);
var usages = GetOrCreateLocalFuncUsages(localFunc);
// If this slot is a struct with individually assignable
// fields we need to record each field assignment separately,
// since some fields may be assigned when this read is replayed
VariableIdentifier id = variableBySlot[slot];
var type = id.Symbol.GetTypeOrReturnType().Type;
Debug.Assert(!_emptyStructTypeCache.IsEmptyStructType(type));
if (EmptyStructTypeCache.IsTrackableStructType(type))
{
foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(type))
{
int fieldSlot = GetOrCreateSlot(field, slot);
if (fieldSlot > 0 && !State.IsAssigned(fieldSlot))
{
RecordReadInLocalFunction(fieldSlot);
}
}
}
else
{
usages.ReadVars[slot] = true;
}
}
private BitVector GetCapturedBitmask()
{
int n = variableBySlot.Count;
BitVector mask = BitVector.AllSet(n);
for (int slot = 1; slot < n; slot++)
{
mask[slot] = IsCapturedInLocalFunction(slot);
}
return mask;
}
private bool IsCapturedInLocalFunction(int slot)
{
if (slot <= 0) return false;
// Find the root slot, since that would be the only
// slot, if any, that is captured in a local function
var rootVarInfo = variableBySlot[RootSlot(slot)];
var rootSymbol = rootVarInfo.Symbol;
// A variable is captured in a local function iff its
// container is higher in the tree than the nearest
// local function
var nearestLocalFunc = GetNearestLocalFunctionOpt(CurrentSymbol);
return !(nearestLocalFunc is null) && Symbol.IsCaptured(rootSymbol, nearestLocalFunc);
}
private static LocalFunctionSymbol GetNearestLocalFunctionOpt(Symbol symbol)
{
while (symbol != null)
{
if (symbol.Kind == SymbolKind.Method &&
((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction)
{
return (LocalFunctionSymbol)symbol;
}
symbol = symbol.ContainingSymbol;
}
return null;
}
protected override LocalFunctionState LocalFunctionStart(LocalFunctionState startState)
{
// Captured variables are definitely assigned if they are assigned on
// all branches into the local function, so we store all reads from
// possibly unassigned captured variables and later report definite
// assignment errors if any of the captured variables is not assigned
// on a particular branch.
var savedState = CreateLocalFunctionState();
savedState.ReadVars = startState.ReadVars.Clone();
startState.ReadVars.Clear();
return savedState;
}
/// <summary>
/// State changes are handled by the base class. We override to find captured variables that
/// have been read before they were assigned and determine if the set has changed.
/// </summary>
protected override bool LocalFunctionEnd(
LocalFunctionState savedState,
LocalFunctionState currentState,
ref LocalState stateAtReturn)
{
if (currentState.CapturedMask.IsNull)
{
currentState.CapturedMask = GetCapturedBitmask();
currentState.InvertedCapturedMask = currentState.CapturedMask.Clone();
currentState.InvertedCapturedMask.Invert();
}
// Filter the modified state variables to only captured variables
stateAtReturn.Assigned.IntersectWith(currentState.CapturedMask);
if (NonMonotonicState.HasValue)
{
var state = NonMonotonicState.Value;
state.Assigned.UnionWith(currentState.InvertedCapturedMask);
NonMonotonicState = state;
}
// Build a list of variables that are both captured and read before assignment
var capturedAndRead = currentState.ReadVars;
capturedAndRead.IntersectWith(currentState.CapturedMask);
// Union and check to see if there are any changes
return savedState.ReadVars.UnionWith(capturedAndRead);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class DefiniteAssignmentPass
{
internal sealed class LocalFunctionState : AbstractLocalFunctionState
{
public BitVector ReadVars = BitVector.Empty;
public BitVector CapturedMask = BitVector.Null;
public BitVector InvertedCapturedMask = BitVector.Null;
public LocalFunctionState(LocalState stateFromBottom, LocalState stateFromTop)
: base(stateFromBottom, stateFromTop)
{ }
}
protected override LocalFunctionState CreateLocalFunctionState(LocalFunctionSymbol symbol)
=> CreateLocalFunctionState();
private LocalFunctionState CreateLocalFunctionState()
=> new LocalFunctionState(
// The bottom state should assume all variables, even new ones, are assigned
new LocalState(BitVector.AllSet(variableBySlot.Count), normalizeToBottom: true),
UnreachableState());
protected override void VisitLocalFunctionUse(
LocalFunctionSymbol localFunc,
LocalFunctionState localFunctionState,
SyntaxNode syntax,
bool isCall)
{
_usedLocalFunctions.Add(localFunc);
// Check variables that were read before being definitely assigned.
var reads = localFunctionState.ReadVars;
// Start at slot 1 (slot 0 just indicates reachability)
for (int slot = 1; slot < reads.Capacity; slot++)
{
if (reads[slot])
{
var symbol = variableBySlot[slot].Symbol;
CheckIfAssignedDuringLocalFunctionReplay(symbol, syntax, slot);
}
}
base.VisitLocalFunctionUse(localFunc, localFunctionState, syntax, isCall);
}
/// <summary>
/// Check that the given variable is definitely assigned when replaying local function
/// reads. If not, produce an error.
/// </summary>
/// <remarks>
/// Specifying the slot manually may be necessary if the symbol is a field,
/// in which case <see cref="LocalDataFlowPass{TLocalState, TLocalFunctionState}.VariableSlot(Symbol, int)"/>
/// will not know which containing slot to look for.
/// </remarks>
private void CheckIfAssignedDuringLocalFunctionReplay(Symbol symbol, SyntaxNode node, int slot)
{
Debug.Assert(!IsConditionalState);
if ((object)symbol != null)
{
NoteRead(symbol);
if (this.State.Reachable)
{
if (slot >= this.State.Assigned.Capacity)
{
Normalize(ref this.State);
}
if (slot > 0 && !this.State.IsAssigned(slot))
{
// Local functions can "call forward" to after a variable has
// been declared but before it has been assigned, so we can never
// consider the declaration location when reporting errors.
ReportUnassignedIfNotCapturedInLocalFunction(symbol, node, slot, skipIfUseBeforeDeclaration: false);
}
}
}
}
private void RecordReadInLocalFunction(int slot)
{
var localFunc = GetNearestLocalFunctionOpt(CurrentSymbol);
Debug.Assert(localFunc != null);
var usages = GetOrCreateLocalFuncUsages(localFunc);
// If this slot is a struct with individually assignable
// fields we need to record each field assignment separately,
// since some fields may be assigned when this read is replayed
VariableIdentifier id = variableBySlot[slot];
var type = id.Symbol.GetTypeOrReturnType().Type;
Debug.Assert(!_emptyStructTypeCache.IsEmptyStructType(type));
if (EmptyStructTypeCache.IsTrackableStructType(type))
{
foreach (var field in _emptyStructTypeCache.GetStructInstanceFields(type))
{
int fieldSlot = GetOrCreateSlot(field, slot);
if (fieldSlot > 0 && !State.IsAssigned(fieldSlot))
{
RecordReadInLocalFunction(fieldSlot);
}
}
}
else
{
usages.ReadVars[slot] = true;
}
}
private BitVector GetCapturedBitmask()
{
int n = variableBySlot.Count;
BitVector mask = BitVector.AllSet(n);
for (int slot = 1; slot < n; slot++)
{
mask[slot] = IsCapturedInLocalFunction(slot);
}
return mask;
}
private bool IsCapturedInLocalFunction(int slot)
{
if (slot <= 0) return false;
// Find the root slot, since that would be the only
// slot, if any, that is captured in a local function
var rootVarInfo = variableBySlot[RootSlot(slot)];
var rootSymbol = rootVarInfo.Symbol;
// A variable is captured in a local function iff its
// container is higher in the tree than the nearest
// local function
var nearestLocalFunc = GetNearestLocalFunctionOpt(CurrentSymbol);
return !(nearestLocalFunc is null) && Symbol.IsCaptured(rootSymbol, nearestLocalFunc);
}
private static LocalFunctionSymbol GetNearestLocalFunctionOpt(Symbol symbol)
{
while (symbol != null)
{
if (symbol.Kind == SymbolKind.Method &&
((MethodSymbol)symbol).MethodKind == MethodKind.LocalFunction)
{
return (LocalFunctionSymbol)symbol;
}
symbol = symbol.ContainingSymbol;
}
return null;
}
protected override LocalFunctionState LocalFunctionStart(LocalFunctionState startState)
{
// Captured variables are definitely assigned if they are assigned on
// all branches into the local function, so we store all reads from
// possibly unassigned captured variables and later report definite
// assignment errors if any of the captured variables is not assigned
// on a particular branch.
var savedState = CreateLocalFunctionState();
savedState.ReadVars = startState.ReadVars.Clone();
startState.ReadVars.Clear();
return savedState;
}
/// <summary>
/// State changes are handled by the base class. We override to find captured variables that
/// have been read before they were assigned and determine if the set has changed.
/// </summary>
protected override bool LocalFunctionEnd(
LocalFunctionState savedState,
LocalFunctionState currentState,
ref LocalState stateAtReturn)
{
if (currentState.CapturedMask.IsNull)
{
currentState.CapturedMask = GetCapturedBitmask();
currentState.InvertedCapturedMask = currentState.CapturedMask.Clone();
currentState.InvertedCapturedMask.Invert();
}
// Filter the modified state variables to only captured variables
stateAtReturn.Assigned.IntersectWith(currentState.CapturedMask);
if (NonMonotonicState.HasValue)
{
var state = NonMonotonicState.Value;
state.Assigned.UnionWith(currentState.InvertedCapturedMask);
NonMonotonicState = state;
}
// Build a list of variables that are both captured and read before assignment
var capturedAndRead = currentState.ReadVars;
capturedAndRead.IntersectWith(currentState.CapturedMask);
// Union and check to see if there are any changes
return savedState.ReadVars.UnionWith(capturedAndRead);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Tests/UseAutoProperty/UseAutoPropertyTests.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;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UseAutoProperty;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseAutoProperty
{
public class UseAutoPropertyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseAutoPropertyTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseAutoPropertyAnalyzer(), GetCSharpUseAutoPropertyCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField_FileScopedNamespace()
{
await TestInRegularAndScript1Async(
@"
namespace N;
class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"
namespace N;
class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField_InRecord()
{
await TestInRegularAndScript1Async(
@"record Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"record Class
{
int P { get; }
}", new TestParameters(TestOptions.RegularPreview));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable1()
{
// โ The expected outcome of this test should not change.
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|MutableInt? i|];
MutableInt? P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly MutableInt? i|];
MutableInt? P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }",
@"class Class
{
MutableInt? P { get; }
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable3()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int? i|];
int? P
{
get
{
return i;
}
}
}",
@"class Class
{
int? P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable4()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly int? i|];
int? P
{
get
{
return i;
}
}
}",
@"class Class
{
int? P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable5()
{
// Recursive type check
await TestMissingInRegularAndScriptAsync(
@"using System;
class Class
{
[|Nullable<MutableInt?> i|];
Nullable<MutableInt?> P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestMutableValueType1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|MutableInt i|];
MutableInt P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestMutableValueType2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly MutableInt i|];
MutableInt P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }",
@"class Class
{
MutableInt P { get; }
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestMutableValueType3()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|MutableInt i|];
MutableInt P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value { get; set; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|ErrorType i|];
ErrorType P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly ErrorType i|];
ErrorType P
{
get
{
return i;
}
}
}",
@"class Class
{
ErrorType P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType3()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|ErrorType? i|];
ErrorType? P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType4()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly ErrorType? i|];
ErrorType? P
{
get
{
return i;
}
}
}",
@"class Class
{
ErrorType? P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType5()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|ErrorType[] i|];
ErrorType[] P
{
get
{
return i;
}
}
}",
@"class Class
{
ErrorType[] P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestCSharp5_1()
{
await TestAsync(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
}
}",
@"class Class
{
public int P { get; private set; }
}",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestCSharp5_2()
{
await TestMissingAsync(
@"class Class
{
[|readonly int i|];
int P
{
get
{
return i;
}
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i = 1|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestInitializer_CSharp5()
{
await TestMissingAsync(
@"class Class
{
[|int i = 1|];
int P
{
get
{
return i;
}
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromProperty()
{
await TestInRegularAndScript1Async(
@"class Class
{
int i;
[|int P
{
get
{
return i;
}
}|]
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
set
{
i = value;
}
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterWithThis()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return this.i;
}
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleSetterWithThis()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
this.i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetterWithThis()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return this.i;
}
set
{
this.i = value;
}
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterWithMutipleStatements()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
;
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSetterWithMutipleStatements()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
;
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
set
{
;
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetterUseDifferentFields()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
set
{
j = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldAndPropertyHaveDifferentStaticInstance()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|static int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefArgument1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(ref int x)
{
M(ref i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefArgument2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(ref int x)
{
M(ref this.i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInOutArgument()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(out int x)
{
M(out i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInInArgument()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(in int x)
{
M(in i);
}
}");
}
[WorkItem(25429, "https://github.com/dotnet/roslyn/issues/25429")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefExpression()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M()
{
ref int x = ref i;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefExpression_AsCandidateSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M()
{
// because we refer to 'i' statically, it only gets resolved as a candidate symbol
// let's be conservative here and disable the analyzer if we're not sure
ref int x = ref Class.i;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestIfUnrelatedSymbolUsedInRefExpression()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
}
void M()
{
int i;
ref int x = ref i;
ref int y = ref j;
}
}",
@"class Class
{
int j;
int P { get; }
void M()
{
int i;
ref int x = ref i;
ref int y = ref j;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithVirtualProperty()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
public virtual int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithConstField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|const int i|];
int P
{
get
{
return i;
}
}
}");
}
[WorkItem(25379, "https://github.com/dotnet/roslyn/issues/25379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithVolatileField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|volatile int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators1()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|], j, k;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j, k;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators2()
{
await TestInRegularAndScript1Async(
@"class Class
{
int i, [|j|], k;
int P
{
get
{
return j;
}
}
}",
@"class Class
{
int i, k;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators3()
{
await TestInRegularAndScript1Async(
@"class Class
{
int i, j, [|k|];
int P
{
get
{
return k;
}
}
}",
@"class Class
{
int i, j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldAndPropertyInDifferentParts()
{
await TestInRegularAndScript1Async(
@"partial class Class
{
[|int i|];
}
partial class Class
{
int P
{
get
{
return i;
}
}
}",
@"partial class Class
{
}
partial class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithFieldWithAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|[A]
int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUpdateReferences()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class()
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUpdateReferencesConflictResolution()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class(int P)
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class(int P)
{
this.P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInConstructor()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class()
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInNotInConstructor1()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public void Goo()
{
i = 1;
}
}",
@"class Class
{
int P { get; set; }
public void Goo()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInNotInConstructor2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
}
public void Goo()
{
i = 1;
}
}",
@"class Class
{
public int P { get; private set; }
public void Goo()
{
P = 1;
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInSimpleExpressionLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action<int> x = _ => i = 1;
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action<int> x = _ => P = 1;
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInSimpleBlockLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action<int> x = _ =>
{
i = 1;
};
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action<int> x = _ =>
{
P = 1;
};
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInParenthesizedExpressionLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action x = () => i = 1;
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action x = () => P = 1;
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInParenthesizedBlockLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action x = () =>
{
i = 1;
};
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action x = () =>
{
P = 1;
};
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInAnonymousMethodInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action x = delegate ()
{
i = 1;
};
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action x = delegate ()
{
P = 1;
};
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInLocalFunctionInConstructor()
{
await TestInRegularAndScript1Async(
@"class C
{
[|int i|];
int P => i;
C()
{
void F()
{
i = 1;
}
}
}",
@"class C
{
int P { get; set; }
C()
{
void F()
{
P = 1;
}
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInExpressionBodiedLocalFunctionInConstructor()
{
await TestInRegularAndScript1Async(
@"class C
{
[|int i|];
int P => i;
C()
{
void F() => i = 1;
}
}",
@"class C
{
int P { get; set; }
C()
{
void F() => P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestReadInExpressionBodiedLocalFunctionInConstructor()
{
await TestInRegularAndScript1Async(
@"class C
{
[|int i|];
int P => i;
C()
{
bool F() => i == 1;
}
}",
@"class C
{
int P { get; }
C()
{
bool F() => P == 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestAlreadyAutoPropertyWithGetterWithNoBody()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
public int [|P|] { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
public int [|P|] { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine1()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P { get { return i; } }
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get { return i; }
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine3()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get { return i; }
set { i = value; }
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_SingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int, string) i|];
(int, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int, string) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithNames_SingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int a, string b) i|];
(int a, string b) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int a, string b) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithDifferentNames_SingleGetterFromField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|readonly (int a, string b) i|];
(int c, string d) P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithOneName_SingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int a, string) i|];
(int a, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int a, string) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_Initializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int, string) i = (1, ""hello"")|];
(int, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int, string) P { get; } = (1, ""hello"");
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_GetterAndSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|(int, string) i|];
(int, string) P
{
get
{
return i;
}
set
{
i = value;
}
}
}");
}
[WorkItem(23215, "https://github.com/dotnet/roslyn/issues/23215")]
[WorkItem(23216, "https://github.com/dotnet/roslyn/issues/23216")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFixAllInDocument()
{
await TestInRegularAndScript1Async(
@"class Class
{
{|FixAllInDocument:int i|};
int P
{
get
{
return i;
}
}
int j;
int Q
{
get
{
return j;
}
}
}",
@"class Class
{
int P { get; }
int Q { get; }
}");
}
[WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExplicitInterfaceImplementationGetterOnly()
{
await TestMissingInRegularAndScriptAsync(@"
namespace RoslynSandbox
{
public interface IFoo
{
object Bar { get; }
}
class Foo : IFoo
{
public Foo(object bar)
{
this.bar = bar;
}
readonly object [|bar|];
object IFoo.Bar
{
get { return bar; }
}
}
}");
}
[WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExplicitInterfaceImplementationGetterAndSetter()
{
await TestMissingInRegularAndScriptAsync(@"
namespace RoslynSandbox
{
public interface IFoo
{
object Bar { get; set; }
}
class Foo : IFoo
{
public Foo(object bar)
{
this.bar = bar;
}
object [|bar|];
object IFoo.Bar
{
get { return bar; }
set { bar = value; }
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetOnly()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P
{
get => i;
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetOnlyWithInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P
{
get => i;
}
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetOnlyWithInitializerAndNeedsSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P
{
get => i;
}
void M() { i = 2; }
}",
@"class Class
{
int P { get; set; } = 1;
void M() { P = 2; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetterAndSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P
{
get => i;
set { i = value; }
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P => i;
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetterWithSetterNeeded()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P => i;
void M() { i = 1; }
}",
@"class Class
{
int P { get; set; }
void M() { P = 1; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetterWithInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P => i;
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedGetterAndSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P {
get => i;
set => i = value;
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedGetterAndSetterWithInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P {
get => i;
set => i = value;
}
}",
@"class Class
{
int P { get; set; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")]
public async Task TestGetterAccessibilityDiffers()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
public int P
{
protected get
{
return i;
}
set
{
i = value;
}
}
}",
@"class Class
{
public int P { protected get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")]
public async Task TestSetterAccessibilityDiffers()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
protected set
{
i = value;
}
}
}",
@"class Class
{
public int P { get; protected set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestPreserveTrailingTrivia1()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
public object Bar => bar;
public int Baz => 0;
}",
@"class Goo
{
public object Bar { get; } = new object();
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestPreserveTrailingTrivia2()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
public object Bar => bar; // prop comment
public int Baz => 0;
}",
@"class Goo
{
public object Bar { get; } = new object(); // prop comment
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestPreserveTrailingTrivia3()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
// doc
public object Bar => bar; // prop comment
public int Baz => 0;
}",
@"class Goo
{
// doc
public object Bar { get; } = new object(); // prop comment
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestKeepLeadingBlank()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
// doc
public object Bar => bar; // prop comment
public int Baz => 0;
}",
@"class Goo
{
// doc
public object Bar { get; } = new object(); // prop comment
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove1()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove2()
{
await TestInRegularAndScript1Async(
@"class Class
{
int j;
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove3()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove4()
{
await TestInRegularAndScript1Async(
@"class Class
{
int j;
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow1()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
[|int i|];
int j;
}",
@"class Class
{
int P { get; }
int j;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow2()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
int j;
[|int i|];
}",
@"class Class
{
int P { get; }
int j;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow3()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
[|int i|];
int j;
}",
@"class Class
{
int P { get; }
int j;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow4()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
int j;
[|int i|];
}",
@"class Class
{
int P { get; }
int j;
}");
}
[WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLineWithDirective()
{
await TestInRegularAndScript1Async(
@"class Class
{
#region Test
[|int i|];
#endregion
int P
{
get
{
return i;
}
}
}",
@"class Class
{
#region Test
#endregion
int P { get; }
}");
}
[WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsWithDirective()
{
await TestInRegularAndScript1Async(
@"class Class
{
#region Test
[|int i|];
int j;
#endregion
int P
{
get
{
return i;
}
}
}",
@"class Class
{
#region Test
int j;
#endregion
int P { get; }
}");
}
[WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLineWithDoubleDirectives()
{
await TestInRegularAndScript1Async(
@"class TestClass
{
#region Field
[|int i|];
#endregion
#region Property
int P
{
get { return i; }
}
#endregion
}",
@"class TestClass
{
#region Field
#endregion
#region Property
int P { get; }
#endregion
}");
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseTabs()
{
await TestInRegularAndScript1Async(
@"public class Foo
{
private readonly object o;
[||]public object O => o;
}",
@"public class Foo
{
public object O { get; }
}", new TestParameters(options: Option(FormattingOptions2.UseTabs, true)));
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseSpaces()
{
await TestInRegularAndScript1Async(
@"public class Foo
{
private readonly object o;
[||]public object O => o;
}",
@"public class Foo
{
public object O { get; }
}", new TestParameters(options: Option(FormattingOptions2.UseTabs, false)));
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseTabs_Editorconfig()
{
await TestInRegularAndScript1Async(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
private readonly object o;
[||]public object O => o;
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = tab
</AnalyzerConfigDocument>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
public object O { get; }
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = tab
</AnalyzerConfigDocument>
</Project>
</Workspace>");
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseSpaces_Editorconfig()
{
await TestInRegularAndScript1Async(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
private readonly object o;
[||]public object O => o;
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = space
</AnalyzerConfigDocument>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
public object O { get; }
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = space
</AnalyzerConfigDocument>
</Project>
</Workspace>");
}
[WorkItem(34783, "https://github.com/dotnet/roslyn/issues/34783")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotOnSerializableType()
{
await TestMissingAsync(
@"
[System.Serializable]
class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}");
}
[WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestPropertyIsReadOnlyAndSetterNeeded()
{
await TestInRegularAndScript1Async(
@"struct S
{
[|int i|];
public readonly int P => i;
public void SetP(int value) => i = value;
}",
@"struct S
{
public int P { get; private set; }
public void SetP(int value) => P = value;
}");
}
[WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestPropertyIsReadOnlyWithNoAccessModifierAndSetterNeeded()
{
await TestInRegularAndScript1Async(
@"struct S
{
[|int i|];
readonly int P => i;
public void SetP(int value) => i = value;
}",
@"struct S
{
int P { get; set; }
public void SetP(int value) => P = value;
}");
}
[WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestPropertyIsReadOnlyAndSetterUnneeded()
{
await TestInRegularAndScript1Async(
@"struct S
{
[|int i|];
public readonly int P => i;
}",
@"struct S
{
public readonly int P { 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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.CSharp.UseAutoProperty;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseAutoProperty
{
public class UseAutoPropertyTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
public UseAutoPropertyTests(ITestOutputHelper logger)
: base(logger)
{
}
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (new CSharpUseAutoPropertyAnalyzer(), GetCSharpUseAutoPropertyCodeFixProvider());
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField_FileScopedNamespace()
{
await TestInRegularAndScript1Async(
@"
namespace N;
class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"
namespace N;
class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromField_InRecord()
{
await TestInRegularAndScript1Async(
@"record Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"record Class
{
int P { get; }
}", new TestParameters(TestOptions.RegularPreview));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable1()
{
// โ The expected outcome of this test should not change.
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|MutableInt? i|];
MutableInt? P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly MutableInt? i|];
MutableInt? P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }",
@"class Class
{
MutableInt? P { get; }
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable3()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int? i|];
int? P
{
get
{
return i;
}
}
}",
@"class Class
{
int? P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable4()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly int? i|];
int? P
{
get
{
return i;
}
}
}",
@"class Class
{
int? P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestNullable5()
{
// Recursive type check
await TestMissingInRegularAndScriptAsync(
@"using System;
class Class
{
[|Nullable<MutableInt?> i|];
Nullable<MutableInt?> P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestMutableValueType1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|MutableInt i|];
MutableInt P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestMutableValueType2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly MutableInt i|];
MutableInt P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value; }",
@"class Class
{
MutableInt P { get; }
}
struct MutableInt { public int Value; }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestMutableValueType3()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|MutableInt i|];
MutableInt P
{
get
{
return i;
}
}
}
struct MutableInt { public int Value { get; set; } }");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|ErrorType i|];
ErrorType P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly ErrorType i|];
ErrorType P
{
get
{
return i;
}
}
}",
@"class Class
{
ErrorType P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType3()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|ErrorType? i|];
ErrorType? P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType4()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly ErrorType? i|];
ErrorType? P
{
get
{
return i;
}
}
}",
@"class Class
{
ErrorType? P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(28511, "https://github.com/dotnet/roslyn/issues/28511")]
public async Task TestErrorType5()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|ErrorType[] i|];
ErrorType[] P
{
get
{
return i;
}
}
}",
@"class Class
{
ErrorType[] P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestCSharp5_1()
{
await TestAsync(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
}
}",
@"class Class
{
public int P { get; private set; }
}",
CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestCSharp5_2()
{
await TestMissingAsync(
@"class Class
{
[|readonly int i|];
int P
{
get
{
return i;
}
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i = 1|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestInitializer_CSharp5()
{
await TestMissingAsync(
@"class Class
{
[|int i = 1|];
int P
{
get
{
return i;
}
}
}", new TestParameters(CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5)));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterFromProperty()
{
await TestInRegularAndScript1Async(
@"class Class
{
int i;
[|int P
{
get
{
return i;
}
}|]
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
set
{
i = value;
}
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleGetterWithThis()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return this.i;
}
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleSetterWithThis()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
this.i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetterWithThis()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return this.i;
}
set
{
this.i = value;
}
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterWithMutipleStatements()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
;
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSetterWithMutipleStatements()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
set
{
;
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSetterWithMultipleStatementsAndGetterWithSingleStatement()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
set
{
;
i = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestGetterAndSetterUseDifferentFields()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
set
{
j = value;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldAndPropertyHaveDifferentStaticInstance()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|static int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefArgument1()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(ref int x)
{
M(ref i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefArgument2()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(ref int x)
{
M(ref this.i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInOutArgument()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(out int x)
{
M(out i);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInInArgument()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M(in int x)
{
M(in i);
}
}");
}
[WorkItem(25429, "https://github.com/dotnet/roslyn/issues/25429")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefExpression()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M()
{
ref int x = ref i;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotIfFieldUsedInRefExpression_AsCandidateSymbol()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
void M()
{
// because we refer to 'i' statically, it only gets resolved as a candidate symbol
// let's be conservative here and disable the analyzer if we're not sure
ref int x = ref Class.i;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestIfUnrelatedSymbolUsedInRefExpression()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
}
void M()
{
int i;
ref int x = ref i;
ref int y = ref j;
}
}",
@"class Class
{
int j;
int P { get; }
void M()
{
int i;
ref int x = ref i;
ref int y = ref j;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithVirtualProperty()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|int i|];
public virtual int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithConstField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|const int i|];
int P
{
get
{
return i;
}
}
}");
}
[WorkItem(25379, "https://github.com/dotnet/roslyn/issues/25379")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithVolatileField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|volatile int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators1()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|], j, k;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j, k;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators2()
{
await TestInRegularAndScript1Async(
@"class Class
{
int i, [|j|], k;
int P
{
get
{
return j;
}
}
}",
@"class Class
{
int i, k;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldWithMultipleDeclarators3()
{
await TestInRegularAndScript1Async(
@"class Class
{
int i, j, [|k|];
int P
{
get
{
return k;
}
}
}",
@"class Class
{
int i, j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFieldAndPropertyInDifferentParts()
{
await TestInRegularAndScript1Async(
@"partial class Class
{
[|int i|];
}
partial class Class
{
int P
{
get
{
return i;
}
}
}",
@"partial class Class
{
}
partial class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotWithFieldWithAttribute()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|[A]
int i|];
int P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUpdateReferences()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class()
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUpdateReferencesConflictResolution()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class(int P)
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class(int P)
{
this.P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInConstructor()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public Class()
{
i = 1;
}
}",
@"class Class
{
int P { get; }
public Class()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInNotInConstructor1()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
public void Goo()
{
i = 1;
}
}",
@"class Class
{
int P { get; set; }
public void Goo()
{
P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInNotInConstructor2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
}
public void Goo()
{
i = 1;
}
}",
@"class Class
{
public int P { get; private set; }
public void Goo()
{
P = 1;
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInSimpleExpressionLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action<int> x = _ => i = 1;
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action<int> x = _ => P = 1;
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInSimpleBlockLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action<int> x = _ =>
{
i = 1;
};
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action<int> x = _ =>
{
P = 1;
};
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInParenthesizedExpressionLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action x = () => i = 1;
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action x = () => P = 1;
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInParenthesizedBlockLambdaInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action x = () =>
{
i = 1;
};
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action x = () =>
{
P = 1;
};
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInAnonymousMethodInConstructor()
{
await TestInRegularAndScript1Async(
@"using System;
class C
{
[|int i|];
int P => i;
C()
{
Action x = delegate ()
{
i = 1;
};
}
}",
@"using System;
class C
{
int P { get; set; }
C()
{
Action x = delegate ()
{
P = 1;
};
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInLocalFunctionInConstructor()
{
await TestInRegularAndScript1Async(
@"class C
{
[|int i|];
int P => i;
C()
{
void F()
{
i = 1;
}
}
}",
@"class C
{
int P { get; set; }
C()
{
void F()
{
P = 1;
}
}
}");
}
[WorkItem(30108, "https://github.com/dotnet/roslyn/issues/30108")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestWriteInExpressionBodiedLocalFunctionInConstructor()
{
await TestInRegularAndScript1Async(
@"class C
{
[|int i|];
int P => i;
C()
{
void F() => i = 1;
}
}",
@"class C
{
int P { get; set; }
C()
{
void F() => P = 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestReadInExpressionBodiedLocalFunctionInConstructor()
{
await TestInRegularAndScript1Async(
@"class C
{
[|int i|];
int P => i;
C()
{
bool F() => i == 1;
}
}",
@"class C
{
int P { get; }
C()
{
bool F() => P == 1;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestAlreadyAutoPropertyWithGetterWithNoBody()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
public int [|P|] { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestAlreadyAutoPropertyWithGetterAndSetterWithNoBody()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
public int [|P|] { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine1()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P { get { return i; } }
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine2()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get { return i; }
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLine3()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int P
{
get { return i; }
set { i = value; }
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_SingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int, string) i|];
(int, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int, string) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithNames_SingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int a, string b) i|];
(int a, string b) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int a, string b) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithDifferentNames_SingleGetterFromField()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|readonly (int a, string b) i|];
(int c, string d) P
{
get
{
return i;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TupleWithOneName_SingleGetterFromField()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int a, string) i|];
(int a, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int a, string) P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_Initializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|readonly (int, string) i = (1, ""hello"")|];
(int, string) P
{
get
{
return i;
}
}
}",
@"class Class
{
(int, string) P { get; } = (1, ""hello"");
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task Tuple_GetterAndSetter()
{
await TestMissingInRegularAndScriptAsync(
@"class Class
{
[|(int, string) i|];
(int, string) P
{
get
{
return i;
}
set
{
i = value;
}
}
}");
}
[WorkItem(23215, "https://github.com/dotnet/roslyn/issues/23215")]
[WorkItem(23216, "https://github.com/dotnet/roslyn/issues/23216")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestFixAllInDocument()
{
await TestInRegularAndScript1Async(
@"class Class
{
{|FixAllInDocument:int i|};
int P
{
get
{
return i;
}
}
int j;
int Q
{
get
{
return j;
}
}
}",
@"class Class
{
int P { get; }
int Q { get; }
}");
}
[WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExplicitInterfaceImplementationGetterOnly()
{
await TestMissingInRegularAndScriptAsync(@"
namespace RoslynSandbox
{
public interface IFoo
{
object Bar { get; }
}
class Foo : IFoo
{
public Foo(object bar)
{
this.bar = bar;
}
readonly object [|bar|];
object IFoo.Bar
{
get { return bar; }
}
}
}");
}
[WorkItem(23735, "https://github.com/dotnet/roslyn/issues/23735")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExplicitInterfaceImplementationGetterAndSetter()
{
await TestMissingInRegularAndScriptAsync(@"
namespace RoslynSandbox
{
public interface IFoo
{
object Bar { get; set; }
}
class Foo : IFoo
{
public Foo(object bar)
{
this.bar = bar;
}
object [|bar|];
object IFoo.Bar
{
get { return bar; }
set { bar = value; }
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetOnly()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P
{
get => i;
}
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetOnlyWithInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P
{
get => i;
}
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetOnlyWithInitializerAndNeedsSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P
{
get => i;
}
void M() { i = 2; }
}",
@"class Class
{
int P { get; set; } = 1;
void M() { P = 2; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetterAndSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P
{
get => i;
set { i = value; }
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P => i;
}",
@"class Class
{
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetterWithSetterNeeded()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P => i;
void M() { i = 1; }
}",
@"class Class
{
int P { get; set; }
void M() { P = 1; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedMemberGetterWithInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P => i;
}",
@"class Class
{
int P { get; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedGetterAndSetter()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|];
int P {
get => i;
set => i = value;
}
}",
@"class Class
{
int P { get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task ExpressionBodiedGetterAndSetterWithInitializer()
{
await TestInRegularAndScript1Async(
@"class Class
{
int [|i|] = 1;
int P {
get => i;
set => i = value;
}
}",
@"class Class
{
int P { get; set; } = 1;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")]
public async Task TestGetterAccessibilityDiffers()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
public int P
{
protected get
{
return i;
}
set
{
i = value;
}
}
}",
@"class Class
{
public int P { protected get; set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(25401, "https://github.com/dotnet/roslyn/issues/25401")]
public async Task TestSetterAccessibilityDiffers()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
public int P
{
get
{
return i;
}
protected set
{
i = value;
}
}
}",
@"class Class
{
public int P { get; protected set; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestPreserveTrailingTrivia1()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
public object Bar => bar;
public int Baz => 0;
}",
@"class Goo
{
public object Bar { get; } = new object();
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestPreserveTrailingTrivia2()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
public object Bar => bar; // prop comment
public int Baz => 0;
}",
@"class Goo
{
public object Bar { get; } = new object(); // prop comment
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestPreserveTrailingTrivia3()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
// doc
public object Bar => bar; // prop comment
public int Baz => 0;
}",
@"class Goo
{
// doc
public object Bar { get; } = new object(); // prop comment
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
[WorkItem(26858, "https://github.com/dotnet/roslyn/issues/26858")]
public async Task TestKeepLeadingBlank()
{
await TestInRegularAndScript1Async(
@"class Goo
{
private readonly object [|bar|] = new object();
// doc
public object Bar => bar; // prop comment
public int Baz => 0;
}",
@"class Goo
{
// doc
public object Bar { get; } = new object(); // prop comment
public int Baz => 0;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove1()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove2()
{
await TestInRegularAndScript1Async(
@"class Class
{
int j;
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove3()
{
await TestInRegularAndScript1Async(
@"class Class
{
[|int i|];
int j;
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsAbove4()
{
await TestInRegularAndScript1Async(
@"class Class
{
int j;
[|int i|];
int P
{
get
{
return i;
}
}
}",
@"class Class
{
int j;
int P { get; }
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow1()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
[|int i|];
int j;
}",
@"class Class
{
int P { get; }
int j;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow2()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
int j;
[|int i|];
}",
@"class Class
{
int P { get; }
int j;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow3()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
[|int i|];
int j;
}",
@"class Class
{
int P { get; }
int j;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsBelow4()
{
await TestInRegularAndScript1Async(
@"class Class
{
int P
{
get
{
return i;
}
}
int j;
[|int i|];
}",
@"class Class
{
int P { get; }
int j;
}");
}
[WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLineWithDirective()
{
await TestInRegularAndScript1Async(
@"class Class
{
#region Test
[|int i|];
#endregion
int P
{
get
{
return i;
}
}
}",
@"class Class
{
#region Test
#endregion
int P { get; }
}");
}
[WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestMultipleFieldsWithDirective()
{
await TestInRegularAndScript1Async(
@"class Class
{
#region Test
[|int i|];
int j;
#endregion
int P
{
get
{
return i;
}
}
}",
@"class Class
{
#region Test
int j;
#endregion
int P { get; }
}");
}
[WorkItem(27675, "https://github.com/dotnet/roslyn/issues/27675")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestSingleLineWithDoubleDirectives()
{
await TestInRegularAndScript1Async(
@"class TestClass
{
#region Field
[|int i|];
#endregion
#region Property
int P
{
get { return i; }
}
#endregion
}",
@"class TestClass
{
#region Field
#endregion
#region Property
int P { get; }
#endregion
}");
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseTabs()
{
await TestInRegularAndScript1Async(
@"public class Foo
{
private readonly object o;
[||]public object O => o;
}",
@"public class Foo
{
public object O { get; }
}", new TestParameters(options: Option(FormattingOptions2.UseTabs, true)));
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseSpaces()
{
await TestInRegularAndScript1Async(
@"public class Foo
{
private readonly object o;
[||]public object O => o;
}",
@"public class Foo
{
public object O { get; }
}", new TestParameters(options: Option(FormattingOptions2.UseTabs, false)));
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseTabs_Editorconfig()
{
await TestInRegularAndScript1Async(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
private readonly object o;
[||]public object O => o;
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = tab
</AnalyzerConfigDocument>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
public object O { get; }
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = tab
</AnalyzerConfigDocument>
</Project>
</Workspace>");
}
[WorkItem(40622, "https://github.com/dotnet/roslyn/issues/40622")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestUseSpaces_Editorconfig()
{
await TestInRegularAndScript1Async(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
private readonly object o;
[||]public object O => o;
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = space
</AnalyzerConfigDocument>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document FilePath = ""z:\\file.cs"">
public class Foo
{
public object O { get; }
}
</Document>
<AnalyzerConfigDocument FilePath = ""z:\\.editorconfig"">
[*]
indent_style = space
</AnalyzerConfigDocument>
</Project>
</Workspace>");
}
[WorkItem(34783, "https://github.com/dotnet/roslyn/issues/34783")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestNotOnSerializableType()
{
await TestMissingAsync(
@"
[System.Serializable]
class Class
{
[|int i|];
int P
{
get
{
return i;
}
}
}");
}
[WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestPropertyIsReadOnlyAndSetterNeeded()
{
await TestInRegularAndScript1Async(
@"struct S
{
[|int i|];
public readonly int P => i;
public void SetP(int value) => i = value;
}",
@"struct S
{
public int P { get; private set; }
public void SetP(int value) => P = value;
}");
}
[WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestPropertyIsReadOnlyWithNoAccessModifierAndSetterNeeded()
{
await TestInRegularAndScript1Async(
@"struct S
{
[|int i|];
readonly int P => i;
public void SetP(int value) => i = value;
}",
@"struct S
{
int P { get; set; }
public void SetP(int value) => P = value;
}");
}
[WorkItem(47999, "https://github.com/dotnet/roslyn/issues/47999")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseAutoProperty)]
public async Task TestPropertyIsReadOnlyAndSetterUnneeded()
{
await TestInRegularAndScript1Async(
@"struct S
{
[|int i|];
public readonly int P => i;
}",
@"struct S
{
public readonly int P { get; }
}");
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Emit/SemanticEdit.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.Symbols;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Describes a symbol edit between two compilations.
/// For example, an addition of a method, an update of a method, removal of a type, etc.
/// </summary>
public readonly struct SemanticEdit : IEquatable<SemanticEdit>
{
/// <summary>
/// The type of edit.
/// </summary>
public SemanticEditKind Kind { get; }
/// <summary>
/// The symbol from the earlier compilation,
/// or null if the edit represents an addition.
/// </summary>
public ISymbol? OldSymbol { get; }
/// <summary>
/// The symbol from the later compilation,
/// or null if the edit represents a deletion.
/// </summary>
public ISymbol? NewSymbol { get; }
/// <summary>
/// A map from syntax node in the later compilation to syntax node in the previous compilation,
/// or null if <see cref="PreserveLocalVariables"/> is false and the map is not needed or
/// the source of the current method is the same as the source of the previous method.
/// </summary>
/// <remarks>
/// The map does not need to map all syntax nodes in the active method, only those syntax nodes
/// that declare a local or generate a long lived local.
/// </remarks>
public Func<SyntaxNode, SyntaxNode?>? SyntaxMap { get; }
/// <summary>
/// True if the edit is an update of the active method and local values
/// should be preserved; false otherwise.
/// </summary>
public bool PreserveLocalVariables { get; }
/// <summary>
/// Initializes an instance of <see cref="SemanticEdit"/>.
/// </summary>
/// <param name="kind">The type of edit.</param>
/// <param name="oldSymbol">
/// The symbol from the earlier compilation, or null if the edit represents an addition.
/// </param>
/// <param name="newSymbol">
/// The symbol from the later compilation, or null if the edit represents a deletion.
/// </param>
/// <param name="syntaxMap">
/// A map from syntax node in the later compilation to syntax node in the previous compilation,
/// or null if <paramref name="preserveLocalVariables"/> is false and the map is not needed or
/// the source of the current method is the same as the source of the previous method.
/// </param>
/// <param name="preserveLocalVariables">
/// True if the edit is an update of an active method and local values should be preserved; false otherwise.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="oldSymbol"/> or <paramref name="newSymbol"/> is null and the edit isn't a <see cref="SemanticEditKind.Insert"/> or <see cref="SemanticEditKind.Delete"/>, respectively.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="kind"/> is not a valid kind.
/// </exception>
public SemanticEdit(SemanticEditKind kind, ISymbol? oldSymbol, ISymbol? newSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap = null, bool preserveLocalVariables = false)
{
if (oldSymbol == null && kind is not (SemanticEditKind.Insert or SemanticEditKind.Replace))
{
throw new ArgumentNullException(nameof(oldSymbol));
}
if (newSymbol == null && kind != SemanticEditKind.Delete)
{
throw new ArgumentNullException(nameof(newSymbol));
}
if (kind <= SemanticEditKind.None || kind > SemanticEditKind.Replace)
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
Kind = kind;
OldSymbol = oldSymbol;
NewSymbol = newSymbol;
PreserveLocalVariables = preserveLocalVariables;
SyntaxMap = syntaxMap;
}
internal static SemanticEdit Create(SemanticEditKind kind, ISymbolInternal oldSymbol, ISymbolInternal newSymbol, Func<SyntaxNode, SyntaxNode>? syntaxMap = null, bool preserveLocalVariables = false)
=> new SemanticEdit(kind, oldSymbol?.GetISymbol(), newSymbol?.GetISymbol(), syntaxMap, preserveLocalVariables);
public override int GetHashCode()
=> Hash.Combine(OldSymbol, Hash.Combine(NewSymbol, (int)Kind));
public override bool Equals(object? obj)
=> obj is SemanticEdit other && Equals(other);
public bool Equals(SemanticEdit other)
=> Kind == other.Kind
&& (OldSymbol == null ? other.OldSymbol == null : OldSymbol.Equals(other.OldSymbol))
&& (NewSymbol == null ? other.NewSymbol == null : NewSymbol.Equals(other.NewSymbol));
public static bool operator ==(SemanticEdit left, SemanticEdit right)
=> left.Equals(right);
public static bool operator !=(SemanticEdit left, SemanticEdit right)
=> !(left == right);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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.Symbols;
using Roslyn.Utilities;
using System;
namespace Microsoft.CodeAnalysis.Emit
{
/// <summary>
/// Describes a symbol edit between two compilations.
/// For example, an addition of a method, an update of a method, removal of a type, etc.
/// </summary>
public readonly struct SemanticEdit : IEquatable<SemanticEdit>
{
/// <summary>
/// The type of edit.
/// </summary>
public SemanticEditKind Kind { get; }
/// <summary>
/// The symbol from the earlier compilation,
/// or null if the edit represents an addition.
/// </summary>
public ISymbol? OldSymbol { get; }
/// <summary>
/// The symbol from the later compilation,
/// or null if the edit represents a deletion.
/// </summary>
public ISymbol? NewSymbol { get; }
/// <summary>
/// A map from syntax node in the later compilation to syntax node in the previous compilation,
/// or null if <see cref="PreserveLocalVariables"/> is false and the map is not needed or
/// the source of the current method is the same as the source of the previous method.
/// </summary>
/// <remarks>
/// The map does not need to map all syntax nodes in the active method, only those syntax nodes
/// that declare a local or generate a long lived local.
/// </remarks>
public Func<SyntaxNode, SyntaxNode?>? SyntaxMap { get; }
/// <summary>
/// True if the edit is an update of the active method and local values
/// should be preserved; false otherwise.
/// </summary>
public bool PreserveLocalVariables { get; }
/// <summary>
/// Initializes an instance of <see cref="SemanticEdit"/>.
/// </summary>
/// <param name="kind">The type of edit.</param>
/// <param name="oldSymbol">
/// The symbol from the earlier compilation, or null if the edit represents an addition.
/// </param>
/// <param name="newSymbol">
/// The symbol from the later compilation, or null if the edit represents a deletion.
/// </param>
/// <param name="syntaxMap">
/// A map from syntax node in the later compilation to syntax node in the previous compilation,
/// or null if <paramref name="preserveLocalVariables"/> is false and the map is not needed or
/// the source of the current method is the same as the source of the previous method.
/// </param>
/// <param name="preserveLocalVariables">
/// True if the edit is an update of an active method and local values should be preserved; false otherwise.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="oldSymbol"/> or <paramref name="newSymbol"/> is null and the edit isn't a <see cref="SemanticEditKind.Insert"/> or <see cref="SemanticEditKind.Delete"/>, respectively.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="kind"/> is not a valid kind.
/// </exception>
public SemanticEdit(SemanticEditKind kind, ISymbol? oldSymbol, ISymbol? newSymbol, Func<SyntaxNode, SyntaxNode?>? syntaxMap = null, bool preserveLocalVariables = false)
{
if (oldSymbol == null && kind is not (SemanticEditKind.Insert or SemanticEditKind.Replace))
{
throw new ArgumentNullException(nameof(oldSymbol));
}
if (newSymbol == null && kind != SemanticEditKind.Delete)
{
throw new ArgumentNullException(nameof(newSymbol));
}
if (kind <= SemanticEditKind.None || kind > SemanticEditKind.Replace)
{
throw new ArgumentOutOfRangeException(nameof(kind));
}
Kind = kind;
OldSymbol = oldSymbol;
NewSymbol = newSymbol;
PreserveLocalVariables = preserveLocalVariables;
SyntaxMap = syntaxMap;
}
internal static SemanticEdit Create(SemanticEditKind kind, ISymbolInternal oldSymbol, ISymbolInternal newSymbol, Func<SyntaxNode, SyntaxNode>? syntaxMap = null, bool preserveLocalVariables = false)
=> new SemanticEdit(kind, oldSymbol?.GetISymbol(), newSymbol?.GetISymbol(), syntaxMap, preserveLocalVariables);
public override int GetHashCode()
=> Hash.Combine(OldSymbol, Hash.Combine(NewSymbol, (int)Kind));
public override bool Equals(object? obj)
=> obj is SemanticEdit other && Equals(other);
public bool Equals(SemanticEdit other)
=> Kind == other.Kind
&& (OldSymbol == null ? other.OldSymbol == null : OldSymbol.Equals(other.OldSymbol))
&& (NewSymbol == null ? other.NewSymbol == null : NewSymbol.Equals(other.NewSymbol));
public static bool operator ==(SemanticEdit left, SemanticEdit right)
=> left.Equals(right);
public static bool operator !=(SemanticEdit left, SemanticEdit right)
=> !(left == right);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/RemoveRedundantEquality/CSharpRemoveRedundantEqualityDiagnosticAnalyzer.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.RemoveRedundantEquality;
namespace Microsoft.CodeAnalysis.CSharp.RemoveRedundantEquality
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpRemoveRedundantEqualityDiagnosticAnalyzer
: AbstractRemoveRedundantEqualityDiagnosticAnalyzer
{
public CSharpRemoveRedundantEqualityDiagnosticAnalyzer() : base(CSharpSyntaxFacts.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.
using Microsoft.CodeAnalysis.CSharp.LanguageServices;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.RemoveRedundantEquality;
namespace Microsoft.CodeAnalysis.CSharp.RemoveRedundantEquality
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpRemoveRedundantEqualityDiagnosticAnalyzer
: AbstractRemoveRedundantEqualityDiagnosticAnalyzer
{
public CSharpRemoveRedundantEqualityDiagnosticAnalyzer() : base(CSharpSyntaxFacts.Instance)
{
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Shared/Utilities/StreamingProgressTracker.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// Utility class that can be used to track the progress of an operation in a threadsafe manner.
/// </summary>
internal sealed class StreamingProgressTracker : IStreamingProgressTracker
{
private int _completedItems;
private int _totalItems;
private readonly Func<int, int, CancellationToken, ValueTask>? _updateAction;
public StreamingProgressTracker(Func<int, int, CancellationToken, ValueTask>? updateAction = null)
=> _updateAction = updateAction;
public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken)
{
Interlocked.Add(ref _totalItems, count);
return UpdateAsync(cancellationToken);
}
public ValueTask ItemCompletedAsync(CancellationToken cancellationToken)
{
Interlocked.Increment(ref _completedItems);
return UpdateAsync(cancellationToken);
}
private ValueTask UpdateAsync(CancellationToken cancellationToken)
{
if (_updateAction == null)
{
return default;
}
return _updateAction(_completedItems, _totalItems, cancellationToken);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// Utility class that can be used to track the progress of an operation in a threadsafe manner.
/// </summary>
internal sealed class StreamingProgressTracker : IStreamingProgressTracker
{
private int _completedItems;
private int _totalItems;
private readonly Func<int, int, CancellationToken, ValueTask>? _updateAction;
public StreamingProgressTracker(Func<int, int, CancellationToken, ValueTask>? updateAction = null)
=> _updateAction = updateAction;
public ValueTask AddItemsAsync(int count, CancellationToken cancellationToken)
{
Interlocked.Add(ref _totalItems, count);
return UpdateAsync(cancellationToken);
}
public ValueTask ItemCompletedAsync(CancellationToken cancellationToken)
{
Interlocked.Increment(ref _completedItems);
return UpdateAsync(cancellationToken);
}
private ValueTask UpdateAsync(CancellationToken cancellationToken)
{
if (_updateAction == null)
{
return default;
}
return _updateAction(_completedItems, _totalItems, cancellationToken);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/Interactive/AbstractResetInteractiveMenuCommand.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.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.VisualStudio.Services.Interactive;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.CodeAnalysis.Editor;
using System.Threading;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interactive
{
internal abstract class AbstractResetInteractiveMenuCommand
{
protected abstract string ProjectKind { get; }
protected abstract CommandID GetResetInteractiveFromProjectCommandID();
private readonly OleMenuCommandService _menuCommandService;
private readonly IVsMonitorSelection _monitorSelection;
private readonly IComponentModel _componentModel;
private readonly string _contentType;
private readonly Lazy<IResetInteractiveCommand> _resetInteractiveCommand;
private Lazy<IResetInteractiveCommand> ResetInteractiveCommand => _resetInteractiveCommand;
public AbstractResetInteractiveMenuCommand(
string contentType,
OleMenuCommandService menuCommandService,
IVsMonitorSelection monitorSelection,
IComponentModel componentModel)
{
_contentType = contentType;
_menuCommandService = menuCommandService;
_monitorSelection = monitorSelection;
_componentModel = componentModel;
_resetInteractiveCommand = _componentModel.DefaultExportProvider
.GetExports<IResetInteractiveCommand, ContentTypeMetadata>()
.Where(resetInteractiveService => resetInteractiveService.Metadata.ContentTypes.Contains(_contentType))
.SingleOrDefault();
}
internal async Task InitializeResetInteractiveFromProjectCommandAsync()
{
var resetInteractiveFromProjectCommand = new OleMenuCommand(
(sender, args) =>
{
ResetInteractiveCommand.Value.ExecuteResetInteractive();
},
GetResetInteractiveFromProjectCommandID());
resetInteractiveFromProjectCommand.Supported = true;
resetInteractiveFromProjectCommand.BeforeQueryStatus += (_, __) =>
{
GetActiveProject(out var project, out var frameworkName);
var available = ResetInteractiveCommand != null
&& project != null && project.Kind == ProjectKind
&& frameworkName != null && frameworkName.Identifier == ".NETFramework";
resetInteractiveFromProjectCommand.Enabled = available;
resetInteractiveFromProjectCommand.Supported = available;
resetInteractiveFromProjectCommand.Visible = available;
};
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
_menuCommandService.AddCommand(resetInteractiveFromProjectCommand);
}
private bool GetActiveProject(out EnvDTE.Project project, out FrameworkName frameworkName)
{
ThreadHelper.ThrowIfNotOnUIThread();
project = null;
frameworkName = null;
var hierarchyPointer = IntPtr.Zero;
var selectionContainerPointer = IntPtr.Zero;
try
{
Marshal.ThrowExceptionForHR(
_monitorSelection.GetCurrentSelection(
out hierarchyPointer,
out var itemid,
out var multiItemSelect,
out selectionContainerPointer));
if (itemid != (uint)VSConstants.VSITEMID.Root)
{
return false;
}
if (!(Marshal.GetObjectForIUnknown(hierarchyPointer) is IVsHierarchy hierarchy))
{
return false;
}
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out var extensibilityObject));
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID3.VSHPROPID_TargetFrameworkVersion, out var targetFrameworkVersion));
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out var targetFrameworkMonikerObject));
var targetFrameworkMoniker = targetFrameworkMonikerObject as string;
frameworkName = new System.Runtime.Versioning.FrameworkName(targetFrameworkMoniker);
project = extensibilityObject as EnvDTE.Project;
return true;
}
finally
{
if (hierarchyPointer != IntPtr.Zero)
{
Marshal.Release(hierarchyPointer);
}
if (selectionContainerPointer != IntPtr.Zero)
{
Marshal.Release(selectionContainerPointer);
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Roslyn.VisualStudio.Services.Interactive;
using System;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.ComponentModel.Design;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.CodeAnalysis.Editor;
using System.Threading;
using Task = System.Threading.Tasks.Task;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Interactive
{
internal abstract class AbstractResetInteractiveMenuCommand
{
protected abstract string ProjectKind { get; }
protected abstract CommandID GetResetInteractiveFromProjectCommandID();
private readonly OleMenuCommandService _menuCommandService;
private readonly IVsMonitorSelection _monitorSelection;
private readonly IComponentModel _componentModel;
private readonly string _contentType;
private readonly Lazy<IResetInteractiveCommand> _resetInteractiveCommand;
private Lazy<IResetInteractiveCommand> ResetInteractiveCommand => _resetInteractiveCommand;
public AbstractResetInteractiveMenuCommand(
string contentType,
OleMenuCommandService menuCommandService,
IVsMonitorSelection monitorSelection,
IComponentModel componentModel)
{
_contentType = contentType;
_menuCommandService = menuCommandService;
_monitorSelection = monitorSelection;
_componentModel = componentModel;
_resetInteractiveCommand = _componentModel.DefaultExportProvider
.GetExports<IResetInteractiveCommand, ContentTypeMetadata>()
.Where(resetInteractiveService => resetInteractiveService.Metadata.ContentTypes.Contains(_contentType))
.SingleOrDefault();
}
internal async Task InitializeResetInteractiveFromProjectCommandAsync()
{
var resetInteractiveFromProjectCommand = new OleMenuCommand(
(sender, args) =>
{
ResetInteractiveCommand.Value.ExecuteResetInteractive();
},
GetResetInteractiveFromProjectCommandID());
resetInteractiveFromProjectCommand.Supported = true;
resetInteractiveFromProjectCommand.BeforeQueryStatus += (_, __) =>
{
GetActiveProject(out var project, out var frameworkName);
var available = ResetInteractiveCommand != null
&& project != null && project.Kind == ProjectKind
&& frameworkName != null && frameworkName.Identifier == ".NETFramework";
resetInteractiveFromProjectCommand.Enabled = available;
resetInteractiveFromProjectCommand.Supported = available;
resetInteractiveFromProjectCommand.Visible = available;
};
await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
_menuCommandService.AddCommand(resetInteractiveFromProjectCommand);
}
private bool GetActiveProject(out EnvDTE.Project project, out FrameworkName frameworkName)
{
ThreadHelper.ThrowIfNotOnUIThread();
project = null;
frameworkName = null;
var hierarchyPointer = IntPtr.Zero;
var selectionContainerPointer = IntPtr.Zero;
try
{
Marshal.ThrowExceptionForHR(
_monitorSelection.GetCurrentSelection(
out hierarchyPointer,
out var itemid,
out var multiItemSelect,
out selectionContainerPointer));
if (itemid != (uint)VSConstants.VSITEMID.Root)
{
return false;
}
if (!(Marshal.GetObjectForIUnknown(hierarchyPointer) is IVsHierarchy hierarchy))
{
return false;
}
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID.VSHPROPID_ExtObject, out var extensibilityObject));
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID3.VSHPROPID_TargetFrameworkVersion, out var targetFrameworkVersion));
Marshal.ThrowExceptionForHR(
hierarchy.GetProperty((uint)VSConstants.VSITEMID.Root, (int)__VSHPROPID4.VSHPROPID_TargetFrameworkMoniker, out var targetFrameworkMonikerObject));
var targetFrameworkMoniker = targetFrameworkMonikerObject as string;
frameworkName = new System.Runtime.Versioning.FrameworkName(targetFrameworkMoniker);
project = extensibilityObject as EnvDTE.Project;
return true;
}
finally
{
if (hierarchyPointer != IntPtr.Zero)
{
Marshal.Release(hierarchyPointer);
}
if (selectionContainerPointer != IntPtr.Zero)
{
Marshal.Release(selectionContainerPointer);
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceLocal.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
protected override async Task<Document> IntroduceLocalAsync(
SemanticDocument document,
ExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
CancellationToken cancellationToken)
{
var containerToGenerateInto = expression.Ancestors().FirstOrDefault(s =>
s is BlockSyntax || s is ArrowExpressionClauseSyntax || s is LambdaExpressionSyntax);
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant, containerToGenerateInto, cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var modifiers = isConstant
? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
: default;
var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
modifiers,
SyntaxFactory.VariableDeclaration(
GetTypeSyntax(document, expression, cancellationToken),
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
null,
SyntaxFactory.EqualsValueClause(expression.WithoutTrivia())))));
// If we're inserting into a multi-line parent, then add a newline after the local-var
// we're adding. That way we don't end up having it and the starting statement be on
// the same line (which will cause indentation to be computed incorrectly).
var text = await document.Document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!text.AreOnSameLine(containerToGenerateInto.GetFirstToken(), containerToGenerateInto.GetLastToken()))
{
declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
}
switch (containerToGenerateInto)
{
case BlockSyntax block:
return await IntroduceLocalDeclarationIntoBlockAsync(
document, block, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(false);
case ArrowExpressionClauseSyntax arrowExpression:
// this will be null for expression-bodied properties & indexer (not for individual getters & setters, those do have a symbol),
// both of which are a shorthand for the getter and always return a value
var method = document.SemanticModel.GetDeclaredSymbol(arrowExpression.Parent, cancellationToken) as IMethodSymbol;
var createReturnStatement = !method?.ReturnsVoid ?? true;
return RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
document, arrowExpression, expression, newLocalName,
declarationStatement, allOccurrences, createReturnStatement, cancellationToken);
case LambdaExpressionSyntax lambda:
return IntroduceLocalDeclarationIntoLambda(
document, lambda, expression, newLocalName, declarationStatement,
allOccurrences, cancellationToken);
}
throw new InvalidOperationException();
}
private Document IntroduceLocalDeclarationIntoLambda(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
ExpressionSyntax expression,
IdentifierNameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldBody = (ExpressionSyntax)oldLambda.Body;
var isEntireLambdaBodySelected = oldBody.Equals(expression.WalkUpParentheses());
var rewrittenBody = Rewrite(
document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken);
var shouldIncludeReturnStatement = ShouldIncludeReturnStatement(document, oldLambda, cancellationToken);
var newBody = GetNewBlockBodyForLambda(
declarationStatement, isEntireLambdaBodySelected, rewrittenBody, shouldIncludeReturnStatement);
// Add an elastic newline so that the formatter will place this new lambda body across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newLambda = oldLambda.WithBody(newBody);
var newRoot = document.Root.ReplaceNode(oldLambda, newLambda);
return document.Document.WithSyntaxRoot(newRoot);
}
private static bool ShouldIncludeReturnStatement(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
CancellationToken cancellationToken)
{
if (document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType is INamedTypeSymbol delegateType &&
delegateType.DelegateInvokeMethod != null)
{
if (delegateType.DelegateInvokeMethod.ReturnsVoid)
{
return false;
}
// Async lambdas with a Task or ValueTask return type don't need a return statement.
// e.g.:
// Func<int, Task> f = async x => await M2();
//
// After refactoring:
// Func<int, Task> f = async x =>
// {
// Task task = M2();
// await task;
// };
var compilation = document.SemanticModel.Compilation;
var delegateReturnType = delegateType.DelegateInvokeMethod.ReturnType;
if (oldLambda.AsyncKeyword != default && delegateReturnType != null)
{
if ((compilation.TaskType() != null && delegateReturnType.Equals(compilation.TaskType())) ||
(compilation.ValueTaskType() != null && delegateReturnType.Equals(compilation.ValueTaskType())))
{
return false;
}
}
}
return true;
}
private static BlockSyntax GetNewBlockBodyForLambda(
LocalDeclarationStatementSyntax declarationStatement,
bool isEntireLambdaBodySelected,
ExpressionSyntax rewrittenBody,
bool includeReturnStatement)
{
if (includeReturnStatement)
{
// Case 1: The lambda has a non-void return type.
// e.g.:
// Func<int, int> f = x => [|x + 1|];
//
// After refactoring:
// Func<int, int> f = x =>
// {
// var v = x + 1;
// return v;
// };
return SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody));
}
// For lambdas with void return types, we don't need to include the rewritten body if the entire lambda body
// was originally selected for refactoring, as the rewritten body should already be encompassed within the
// declaration statement.
if (isEntireLambdaBodySelected)
{
// Case 2a: The lambda has a void return type, and the user selects the entire lambda body.
// e.g.:
// Action<int> goo = x => [|x.ToString()|];
//
// After refactoring:
// Action<int> goo = x =>
// {
// string v = x.ToString();
// };
return SyntaxFactory.Block(declarationStatement);
}
// Case 2b: The lambda has a void return type, and the user didn't select the entire lambda body.
// e.g.:
// Task.Run(() => File.Copy("src", [|Path.Combine("dir", "file")|]));
//
// After refactoring:
// Task.Run(() =>
// {
// string destFileName = Path.Combine("dir", "file");
// File.Copy("src", destFileName);
// });
return SyntaxFactory.Block(
declarationStatement,
SyntaxFactory.ExpressionStatement(rewrittenBody, SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken)
{
var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);
return typeSymbol.GenerateTypeSyntax();
}
private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
SemanticDocument document,
ArrowExpressionClauseSyntax arrowExpression,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
bool createReturnStatement,
CancellationToken cancellationToken)
{
var oldBody = arrowExpression;
var oldParentingNode = oldBody.Parent;
var leadingTrivia = oldBody.GetLeadingTrivia()
.AddRange(oldBody.ArrowToken.TrailingTrivia);
var newExpression = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken);
var convertedStatement = createReturnStatement
? SyntaxFactory.ReturnStatement(newExpression)
: (StatementSyntax)SyntaxFactory.ExpressionStatement(newExpression);
var newBody = SyntaxFactory.Block(declarationStatement, convertedStatement)
.WithLeadingTrivia(leadingTrivia)
.WithTrailingTrivia(oldBody.GetTrailingTrivia());
// Add an elastic newline so that the formatter will place this new block across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = document.Root.ReplaceNode(oldParentingNode, WithBlockBody(oldParentingNode, newBody));
return document.Document.WithSyntaxRoot(newRoot);
}
private static SyntaxNode WithBlockBody(SyntaxNode node, BlockSyntax body)
{
switch (node)
{
case BasePropertyDeclarationSyntax baseProperty:
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)));
return baseProperty
.TryWithExpressionBody(null)
.WithAccessorList(accessorList)
.TryWithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseProperty);
case AccessorDeclarationSyntax accessor:
return accessor
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(accessor);
case BaseMethodDeclarationSyntax baseMethod:
return baseMethod
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseMethod);
case LocalFunctionStatementSyntax localFunction:
return localFunction
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(localFunction);
default:
throw ExceptionUtilities.UnexpectedValue(node);
}
}
private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync(
SemanticDocument document,
BlockSyntax block,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
SyntaxNode scope = block;
// If we're within a non-static local function, our scope for the new local declaration is expanded to include the enclosing member.
var localFunction = block.GetAncestor<LocalFunctionStatementSyntax>();
if (localFunction != null && !localFunction.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.StaticKeyword)))
{
scope = block.GetAncestor<MemberDeclarationSyntax>();
}
var matches = FindMatches(document, expression, document, scope, allOccurrences, cancellationToken);
Debug.Assert(matches.Contains(expression));
(document, matches) = await ComplexifyParentingStatementsAsync(document, matches, cancellationToken).ConfigureAwait(false);
// Our original expression should have been one of the matches, which were tracked as part
// of complexification, so we can retrieve the latest version of the expression here.
expression = document.Root.GetCurrentNode(expression);
var root = document.Root;
ISet<StatementSyntax> allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => GetApplicableStatementAncestors(expr)));
SyntaxNode innermostCommonBlock;
var innermostStatements = new HashSet<StatementSyntax>(matches.Select(expr => GetApplicableStatementAncestors(expr).First()));
if (innermostStatements.Count == 1)
{
// if there was only one match, or all the matches came from the same statement
var statement = innermostStatements.Single();
// and the statement is an embedded statement without a block, we want to generate one
// around this statement rather than continue going up to find an actual block
if (!IsBlockLike(statement.Parent))
{
root = root.TrackNodes(allAffectedStatements.Concat(new SyntaxNode[] { expression, statement }));
root = root.ReplaceNode(root.GetCurrentNode(statement),
SyntaxFactory.Block(root.GetCurrentNode(statement)).WithAdditionalAnnotations(Formatter.Annotation));
expression = root.GetCurrentNode(expression);
allAffectedStatements = allAffectedStatements.Select(root.GetCurrentNode).ToSet();
statement = root.GetCurrentNode(statement);
}
innermostCommonBlock = statement.Parent;
}
else
{
innermostCommonBlock = innermostStatements.FindInnermostCommonNode(IsBlockLike);
}
var firstStatementAffectedIndex = GetFirstStatementAffectedIndex(innermostCommonBlock, matches, GetStatements(innermostCommonBlock).IndexOf(allAffectedStatements.Contains));
var newInnerMostBlock = Rewrite(
document, expression, newLocalName, document, innermostCommonBlock, allOccurrences, cancellationToken);
var statements = InsertWithinTriviaOfNext(GetStatements(newInnerMostBlock), declarationStatement, firstStatementAffectedIndex);
var finalInnerMostBlock = WithStatements(newInnerMostBlock, statements);
var newRoot = root.ReplaceNode(innermostCommonBlock, finalInnerMostBlock);
return document.Document.WithSyntaxRoot(newRoot);
}
private static IEnumerable<StatementSyntax> GetApplicableStatementAncestors(ExpressionSyntax expr)
{
foreach (var statement in expr.GetAncestorsOrThis<StatementSyntax>())
{
// When determining where to put a local, we don't want to put it between the `else`
// and `if` of a compound if-statement.
if (statement.Kind() == SyntaxKind.IfStatement &&
statement.IsParentKind(SyntaxKind.ElseClause))
{
continue;
}
yield return statement;
}
}
private static int GetFirstStatementAffectedIndex(SyntaxNode innermostCommonBlock, ISet<ExpressionSyntax> matches, int firstStatementAffectedIndex)
{
// If a local function is involved, we have to make sure the new declaration is placed:
// 1. Before all calls to local functions that use the variable.
// 2. Before the local function(s) themselves.
// 3. Before all matches, i.e. places in the code where the new declaration will replace existing code.
// Cases (2) and (3) are already covered by the 'firstStatementAffectedIndex' parameter. Thus, all we have to do is ensure we consider (1) when
// determining where to place our new declaration.
// Find all the local functions within the scope that will use the new declaration.
var localFunctions = innermostCommonBlock.DescendantNodes().Where(node => node.IsKind(SyntaxKind.LocalFunctionStatement) && matches.Any(match => match.Span.OverlapsWith(node.Span)));
if (localFunctions.IsEmpty())
{
return firstStatementAffectedIndex;
}
var localFunctionIdentifiers = localFunctions.Select(node => ((LocalFunctionStatementSyntax)node).Identifier.ValueText);
// Find all calls to the applicable local functions within the scope.
var localFunctionCalls = innermostCommonBlock.DescendantNodes().Where(node => node is InvocationExpressionSyntax invocationExpression &&
invocationExpression.Expression.GetRightmostName() != null &&
!invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
localFunctionIdentifiers.Contains(invocationExpression.Expression.GetRightmostName().Identifier.ValueText));
if (localFunctionCalls.IsEmpty())
{
return firstStatementAffectedIndex;
}
// Find which call is the earliest.
var earliestLocalFunctionCall = localFunctionCalls.Min(node => node.SpanStart);
var statementsInBlock = GetStatements(innermostCommonBlock);
// Check if our earliest call is before all local function declarations and all matches, and if so, place our new declaration there.
var earliestLocalFunctionCallIndex = statementsInBlock.IndexOf(s => s.Span.Contains(earliestLocalFunctionCall));
return Math.Min(earliestLocalFunctionCallIndex, firstStatementAffectedIndex);
}
private static SyntaxList<StatementSyntax> InsertWithinTriviaOfNext(
SyntaxList<StatementSyntax> oldStatements,
StatementSyntax newStatement,
int statementIndex)
{
var nextStatement = oldStatements.ElementAtOrDefault(statementIndex);
if (nextStatement == null)
return oldStatements.Insert(statementIndex, newStatement);
// Grab all the trivia before the line the next statement is on and move it to the new node.
var nextStatementLeading = nextStatement.GetLeadingTrivia();
var precedingEndOfLine = nextStatementLeading.LastOrDefault(t => t.Kind() == SyntaxKind.EndOfLineTrivia);
if (precedingEndOfLine == default)
{
return oldStatements.ReplaceRange(
nextStatement, new[] { newStatement, nextStatement });
}
var endOfLineIndex = nextStatementLeading.IndexOf(precedingEndOfLine) + 1;
return oldStatements.ReplaceRange(
nextStatement, new[]
{
newStatement.WithLeadingTrivia(nextStatementLeading.Take(endOfLineIndex)),
nextStatement.WithLeadingTrivia(nextStatementLeading.Skip(endOfLineIndex)),
});
}
private static bool IsBlockLike(SyntaxNode node) => node is BlockSyntax || node is SwitchSectionSyntax;
private static SyntaxList<StatementSyntax> GetStatements(SyntaxNode blockLike)
=> blockLike switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
private static SyntaxNode WithStatements(SyntaxNode blockLike, SyntaxList<StatementSyntax> statements)
=> blockLike switch
{
BlockSyntax block => block.WithStatements(statements),
SwitchSectionSyntax switchSection => switchSection.WithStatements(statements),
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
protected override async Task<Document> IntroduceLocalAsync(
SemanticDocument document,
ExpressionSyntax expression,
bool allOccurrences,
bool isConstant,
CancellationToken cancellationToken)
{
var containerToGenerateInto = expression.Ancestors().FirstOrDefault(s =>
s is BlockSyntax || s is ArrowExpressionClauseSyntax || s is LambdaExpressionSyntax);
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant, containerToGenerateInto, cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var modifiers = isConstant
? SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.ConstKeyword))
: default;
var declarationStatement = SyntaxFactory.LocalDeclarationStatement(
modifiers,
SyntaxFactory.VariableDeclaration(
GetTypeSyntax(document, expression, cancellationToken),
SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
null,
SyntaxFactory.EqualsValueClause(expression.WithoutTrivia())))));
// If we're inserting into a multi-line parent, then add a newline after the local-var
// we're adding. That way we don't end up having it and the starting statement be on
// the same line (which will cause indentation to be computed incorrectly).
var text = await document.Document.GetTextAsync(cancellationToken).ConfigureAwait(false);
if (!text.AreOnSameLine(containerToGenerateInto.GetFirstToken(), containerToGenerateInto.GetLastToken()))
{
declarationStatement = declarationStatement.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed);
}
switch (containerToGenerateInto)
{
case BlockSyntax block:
return await IntroduceLocalDeclarationIntoBlockAsync(
document, block, expression, newLocalName, declarationStatement, allOccurrences, cancellationToken).ConfigureAwait(false);
case ArrowExpressionClauseSyntax arrowExpression:
// this will be null for expression-bodied properties & indexer (not for individual getters & setters, those do have a symbol),
// both of which are a shorthand for the getter and always return a value
var method = document.SemanticModel.GetDeclaredSymbol(arrowExpression.Parent, cancellationToken) as IMethodSymbol;
var createReturnStatement = !method?.ReturnsVoid ?? true;
return RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
document, arrowExpression, expression, newLocalName,
declarationStatement, allOccurrences, createReturnStatement, cancellationToken);
case LambdaExpressionSyntax lambda:
return IntroduceLocalDeclarationIntoLambda(
document, lambda, expression, newLocalName, declarationStatement,
allOccurrences, cancellationToken);
}
throw new InvalidOperationException();
}
private Document IntroduceLocalDeclarationIntoLambda(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
ExpressionSyntax expression,
IdentifierNameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldBody = (ExpressionSyntax)oldLambda.Body;
var isEntireLambdaBodySelected = oldBody.Equals(expression.WalkUpParentheses());
var rewrittenBody = Rewrite(
document, expression, newLocalName, document, oldBody, allOccurrences, cancellationToken);
var shouldIncludeReturnStatement = ShouldIncludeReturnStatement(document, oldLambda, cancellationToken);
var newBody = GetNewBlockBodyForLambda(
declarationStatement, isEntireLambdaBodySelected, rewrittenBody, shouldIncludeReturnStatement);
// Add an elastic newline so that the formatter will place this new lambda body across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newLambda = oldLambda.WithBody(newBody);
var newRoot = document.Root.ReplaceNode(oldLambda, newLambda);
return document.Document.WithSyntaxRoot(newRoot);
}
private static bool ShouldIncludeReturnStatement(
SemanticDocument document,
LambdaExpressionSyntax oldLambda,
CancellationToken cancellationToken)
{
if (document.SemanticModel.GetTypeInfo(oldLambda, cancellationToken).ConvertedType is INamedTypeSymbol delegateType &&
delegateType.DelegateInvokeMethod != null)
{
if (delegateType.DelegateInvokeMethod.ReturnsVoid)
{
return false;
}
// Async lambdas with a Task or ValueTask return type don't need a return statement.
// e.g.:
// Func<int, Task> f = async x => await M2();
//
// After refactoring:
// Func<int, Task> f = async x =>
// {
// Task task = M2();
// await task;
// };
var compilation = document.SemanticModel.Compilation;
var delegateReturnType = delegateType.DelegateInvokeMethod.ReturnType;
if (oldLambda.AsyncKeyword != default && delegateReturnType != null)
{
if ((compilation.TaskType() != null && delegateReturnType.Equals(compilation.TaskType())) ||
(compilation.ValueTaskType() != null && delegateReturnType.Equals(compilation.ValueTaskType())))
{
return false;
}
}
}
return true;
}
private static BlockSyntax GetNewBlockBodyForLambda(
LocalDeclarationStatementSyntax declarationStatement,
bool isEntireLambdaBodySelected,
ExpressionSyntax rewrittenBody,
bool includeReturnStatement)
{
if (includeReturnStatement)
{
// Case 1: The lambda has a non-void return type.
// e.g.:
// Func<int, int> f = x => [|x + 1|];
//
// After refactoring:
// Func<int, int> f = x =>
// {
// var v = x + 1;
// return v;
// };
return SyntaxFactory.Block(declarationStatement, SyntaxFactory.ReturnStatement(rewrittenBody));
}
// For lambdas with void return types, we don't need to include the rewritten body if the entire lambda body
// was originally selected for refactoring, as the rewritten body should already be encompassed within the
// declaration statement.
if (isEntireLambdaBodySelected)
{
// Case 2a: The lambda has a void return type, and the user selects the entire lambda body.
// e.g.:
// Action<int> goo = x => [|x.ToString()|];
//
// After refactoring:
// Action<int> goo = x =>
// {
// string v = x.ToString();
// };
return SyntaxFactory.Block(declarationStatement);
}
// Case 2b: The lambda has a void return type, and the user didn't select the entire lambda body.
// e.g.:
// Task.Run(() => File.Copy("src", [|Path.Combine("dir", "file")|]));
//
// After refactoring:
// Task.Run(() =>
// {
// string destFileName = Path.Combine("dir", "file");
// File.Copy("src", destFileName);
// });
return SyntaxFactory.Block(
declarationStatement,
SyntaxFactory.ExpressionStatement(rewrittenBody, SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
}
private static TypeSyntax GetTypeSyntax(SemanticDocument document, ExpressionSyntax expression, CancellationToken cancellationToken)
{
var typeSymbol = GetTypeSymbol(document, expression, cancellationToken);
return typeSymbol.GenerateTypeSyntax();
}
private Document RewriteExpressionBodiedMemberAndIntroduceLocalDeclaration(
SemanticDocument document,
ArrowExpressionClauseSyntax arrowExpression,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
bool createReturnStatement,
CancellationToken cancellationToken)
{
var oldBody = arrowExpression;
var oldParentingNode = oldBody.Parent;
var leadingTrivia = oldBody.GetLeadingTrivia()
.AddRange(oldBody.ArrowToken.TrailingTrivia);
var newExpression = Rewrite(document, expression, newLocalName, document, oldBody.Expression, allOccurrences, cancellationToken);
var convertedStatement = createReturnStatement
? SyntaxFactory.ReturnStatement(newExpression)
: (StatementSyntax)SyntaxFactory.ExpressionStatement(newExpression);
var newBody = SyntaxFactory.Block(declarationStatement, convertedStatement)
.WithLeadingTrivia(leadingTrivia)
.WithTrailingTrivia(oldBody.GetTrailingTrivia());
// Add an elastic newline so that the formatter will place this new block across multiple lines.
newBody = newBody.WithOpenBraceToken(newBody.OpenBraceToken.WithAppendedTrailingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed))
.WithAdditionalAnnotations(Formatter.Annotation);
var newRoot = document.Root.ReplaceNode(oldParentingNode, WithBlockBody(oldParentingNode, newBody));
return document.Document.WithSyntaxRoot(newRoot);
}
private static SyntaxNode WithBlockBody(SyntaxNode node, BlockSyntax body)
{
switch (node)
{
case BasePropertyDeclarationSyntax baseProperty:
var accessorList = SyntaxFactory.AccessorList(SyntaxFactory.SingletonList(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration, body)));
return baseProperty
.TryWithExpressionBody(null)
.WithAccessorList(accessorList)
.TryWithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseProperty);
case AccessorDeclarationSyntax accessor:
return accessor
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(accessor);
case BaseMethodDeclarationSyntax baseMethod:
return baseMethod
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(baseMethod);
case LocalFunctionStatementSyntax localFunction:
return localFunction
.WithExpressionBody(null)
.WithBody(body)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.None))
.WithTriviaFrom(localFunction);
default:
throw ExceptionUtilities.UnexpectedValue(node);
}
}
private async Task<Document> IntroduceLocalDeclarationIntoBlockAsync(
SemanticDocument document,
BlockSyntax block,
ExpressionSyntax expression,
NameSyntax newLocalName,
LocalDeclarationStatementSyntax declarationStatement,
bool allOccurrences,
CancellationToken cancellationToken)
{
declarationStatement = declarationStatement.WithAdditionalAnnotations(Formatter.Annotation);
SyntaxNode scope = block;
// If we're within a non-static local function, our scope for the new local declaration is expanded to include the enclosing member.
var localFunction = block.GetAncestor<LocalFunctionStatementSyntax>();
if (localFunction != null && !localFunction.Modifiers.Any(modifier => modifier.IsKind(SyntaxKind.StaticKeyword)))
{
scope = block.GetAncestor<MemberDeclarationSyntax>();
}
var matches = FindMatches(document, expression, document, scope, allOccurrences, cancellationToken);
Debug.Assert(matches.Contains(expression));
(document, matches) = await ComplexifyParentingStatementsAsync(document, matches, cancellationToken).ConfigureAwait(false);
// Our original expression should have been one of the matches, which were tracked as part
// of complexification, so we can retrieve the latest version of the expression here.
expression = document.Root.GetCurrentNode(expression);
var root = document.Root;
ISet<StatementSyntax> allAffectedStatements = new HashSet<StatementSyntax>(matches.SelectMany(expr => GetApplicableStatementAncestors(expr)));
SyntaxNode innermostCommonBlock;
var innermostStatements = new HashSet<StatementSyntax>(matches.Select(expr => GetApplicableStatementAncestors(expr).First()));
if (innermostStatements.Count == 1)
{
// if there was only one match, or all the matches came from the same statement
var statement = innermostStatements.Single();
// and the statement is an embedded statement without a block, we want to generate one
// around this statement rather than continue going up to find an actual block
if (!IsBlockLike(statement.Parent))
{
root = root.TrackNodes(allAffectedStatements.Concat(new SyntaxNode[] { expression, statement }));
root = root.ReplaceNode(root.GetCurrentNode(statement),
SyntaxFactory.Block(root.GetCurrentNode(statement)).WithAdditionalAnnotations(Formatter.Annotation));
expression = root.GetCurrentNode(expression);
allAffectedStatements = allAffectedStatements.Select(root.GetCurrentNode).ToSet();
statement = root.GetCurrentNode(statement);
}
innermostCommonBlock = statement.Parent;
}
else
{
innermostCommonBlock = innermostStatements.FindInnermostCommonNode(IsBlockLike);
}
var firstStatementAffectedIndex = GetFirstStatementAffectedIndex(innermostCommonBlock, matches, GetStatements(innermostCommonBlock).IndexOf(allAffectedStatements.Contains));
var newInnerMostBlock = Rewrite(
document, expression, newLocalName, document, innermostCommonBlock, allOccurrences, cancellationToken);
var statements = InsertWithinTriviaOfNext(GetStatements(newInnerMostBlock), declarationStatement, firstStatementAffectedIndex);
var finalInnerMostBlock = WithStatements(newInnerMostBlock, statements);
var newRoot = root.ReplaceNode(innermostCommonBlock, finalInnerMostBlock);
return document.Document.WithSyntaxRoot(newRoot);
}
private static IEnumerable<StatementSyntax> GetApplicableStatementAncestors(ExpressionSyntax expr)
{
foreach (var statement in expr.GetAncestorsOrThis<StatementSyntax>())
{
// When determining where to put a local, we don't want to put it between the `else`
// and `if` of a compound if-statement.
if (statement.Kind() == SyntaxKind.IfStatement &&
statement.IsParentKind(SyntaxKind.ElseClause))
{
continue;
}
yield return statement;
}
}
private static int GetFirstStatementAffectedIndex(SyntaxNode innermostCommonBlock, ISet<ExpressionSyntax> matches, int firstStatementAffectedIndex)
{
// If a local function is involved, we have to make sure the new declaration is placed:
// 1. Before all calls to local functions that use the variable.
// 2. Before the local function(s) themselves.
// 3. Before all matches, i.e. places in the code where the new declaration will replace existing code.
// Cases (2) and (3) are already covered by the 'firstStatementAffectedIndex' parameter. Thus, all we have to do is ensure we consider (1) when
// determining where to place our new declaration.
// Find all the local functions within the scope that will use the new declaration.
var localFunctions = innermostCommonBlock.DescendantNodes().Where(node => node.IsKind(SyntaxKind.LocalFunctionStatement) && matches.Any(match => match.Span.OverlapsWith(node.Span)));
if (localFunctions.IsEmpty())
{
return firstStatementAffectedIndex;
}
var localFunctionIdentifiers = localFunctions.Select(node => ((LocalFunctionStatementSyntax)node).Identifier.ValueText);
// Find all calls to the applicable local functions within the scope.
var localFunctionCalls = innermostCommonBlock.DescendantNodes().Where(node => node is InvocationExpressionSyntax invocationExpression &&
invocationExpression.Expression.GetRightmostName() != null &&
!invocationExpression.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression) &&
localFunctionIdentifiers.Contains(invocationExpression.Expression.GetRightmostName().Identifier.ValueText));
if (localFunctionCalls.IsEmpty())
{
return firstStatementAffectedIndex;
}
// Find which call is the earliest.
var earliestLocalFunctionCall = localFunctionCalls.Min(node => node.SpanStart);
var statementsInBlock = GetStatements(innermostCommonBlock);
// Check if our earliest call is before all local function declarations and all matches, and if so, place our new declaration there.
var earliestLocalFunctionCallIndex = statementsInBlock.IndexOf(s => s.Span.Contains(earliestLocalFunctionCall));
return Math.Min(earliestLocalFunctionCallIndex, firstStatementAffectedIndex);
}
private static SyntaxList<StatementSyntax> InsertWithinTriviaOfNext(
SyntaxList<StatementSyntax> oldStatements,
StatementSyntax newStatement,
int statementIndex)
{
var nextStatement = oldStatements.ElementAtOrDefault(statementIndex);
if (nextStatement == null)
return oldStatements.Insert(statementIndex, newStatement);
// Grab all the trivia before the line the next statement is on and move it to the new node.
var nextStatementLeading = nextStatement.GetLeadingTrivia();
var precedingEndOfLine = nextStatementLeading.LastOrDefault(t => t.Kind() == SyntaxKind.EndOfLineTrivia);
if (precedingEndOfLine == default)
{
return oldStatements.ReplaceRange(
nextStatement, new[] { newStatement, nextStatement });
}
var endOfLineIndex = nextStatementLeading.IndexOf(precedingEndOfLine) + 1;
return oldStatements.ReplaceRange(
nextStatement, new[]
{
newStatement.WithLeadingTrivia(nextStatementLeading.Take(endOfLineIndex)),
nextStatement.WithLeadingTrivia(nextStatementLeading.Skip(endOfLineIndex)),
});
}
private static bool IsBlockLike(SyntaxNode node) => node is BlockSyntax || node is SwitchSectionSyntax;
private static SyntaxList<StatementSyntax> GetStatements(SyntaxNode blockLike)
=> blockLike switch
{
BlockSyntax block => block.Statements,
SwitchSectionSyntax switchSection => switchSection.Statements,
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
private static SyntaxNode WithStatements(SyntaxNode blockLike, SyntaxList<StatementSyntax> statements)
=> blockLike switch
{
BlockSyntax block => block.WithStatements(statements),
SwitchSectionSyntax switchSection => switchSection.WithStatements(statements),
_ => throw ExceptionUtilities.UnexpectedValue(blockLike),
};
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Portable/Symbols/NonMissingModuleSymbol.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A <see cref="NonMissingModuleSymbol"/> is a special kind of <see cref="ModuleSymbol"/> that represents
/// a module that is not missing, i.e. the "real" thing.
/// </summary>
internal abstract class NonMissingModuleSymbol : ModuleSymbol
{
/// <summary>
/// An array of <see cref="AssemblySymbol"/> objects corresponding to assemblies directly referenced by this module.
/// </summary>
/// <remarks>
/// The contents are provided by ReferenceManager and may not be modified.
/// </remarks>
private ModuleReferences<AssemblySymbol> _moduleReferences;
/// <summary>
/// Does this symbol represent a missing module.
/// </summary>
internal sealed override bool IsMissing
{
get
{
return false;
}
}
/// <summary>
/// Returns an array of assembly identities for assemblies referenced by this module.
/// Items at the same position from GetReferencedAssemblies and from GetReferencedAssemblySymbols
/// should correspond to each other.
/// </summary>
internal sealed override ImmutableArray<AssemblyIdentity> GetReferencedAssemblies()
{
AssertReferencesInitialized();
return _moduleReferences.Identities;
}
/// <summary>
/// Returns an array of AssemblySymbol objects corresponding to assemblies referenced
/// by this module. Items at the same position from GetReferencedAssemblies and
/// from GetReferencedAssemblySymbols should correspond to each other. If reference is
/// not resolved by compiler, GetReferencedAssemblySymbols returns MissingAssemblySymbol in the
/// corresponding item.
/// </summary>
internal sealed override ImmutableArray<AssemblySymbol> GetReferencedAssemblySymbols()
{
AssertReferencesInitialized();
return _moduleReferences.Symbols;
}
internal ImmutableArray<UnifiedAssembly<AssemblySymbol>> GetUnifiedAssemblies()
{
AssertReferencesInitialized();
return _moduleReferences.UnifiedAssemblies;
}
internal override bool HasUnifiedReferences
{
get { return GetUnifiedAssemblies().Length > 0; }
}
internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType)
{
AssertReferencesInitialized();
var ownerModule = this;
var ownerAssembly = ownerModule.ContainingAssembly;
var dependentAssembly = dependentType.ContainingAssembly;
if (ownerAssembly == dependentAssembly)
{
return false;
}
// TODO (tomat): we should report an error/warning for all unified references, not just the first one.
foreach (var unifiedAssembly in GetUnifiedAssemblies())
{
if (!ReferenceEquals(unifiedAssembly.TargetAssembly, dependentAssembly))
{
continue;
}
var referenceId = unifiedAssembly.OriginalReference;
var definitionId = dependentAssembly.Identity;
var involvedAssemblies = ImmutableArray.Create<Symbol>(ownerAssembly, dependentAssembly);
DiagnosticInfo info;
if (definitionId.Version > referenceId.Version)
{
// unified with a definition whose version is higher than the reference
ErrorCode warning = (definitionId.Version.Major == referenceId.Version.Major && definitionId.Version.Minor == referenceId.Version.Minor) ?
ErrorCode.WRN_UnifyReferenceBldRev : ErrorCode.WRN_UnifyReferenceMajMin;
// warning: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy.
info = new CSDiagnosticInfo(
warning,
new object[]
{
referenceId.GetDisplayName(),
ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference
definitionId.GetDisplayName(),
dependentAssembly.Name
},
involvedAssemblies,
ImmutableArray<Location>.Empty);
}
else
{
// unified with a definition whose version is lower than the reference
// error: Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}'
info = new CSDiagnosticInfo(
ErrorCode.ERR_AssemblyMatchBadVersion,
new object[]
{
ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference
ownerAssembly.Identity.GetDisplayName(),
referenceId.GetDisplayName(),
dependentAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference
definitionId.GetDisplayName()
},
involvedAssemblies,
ImmutableArray<Location>.Empty);
}
if (MergeUseSiteDiagnostics(ref result, info))
{
return true;
}
}
return false;
}
/// <summary>
/// A helper method for ReferenceManager to set assembly identities for assemblies
/// referenced by this module and corresponding AssemblySymbols.
/// </summary>
internal override void SetReferences(ModuleReferences<AssemblySymbol> moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly = null)
{
Debug.Assert(moduleReferences != null);
AssertReferencesUninitialized();
_moduleReferences = moduleReferences;
}
[Conditional("DEBUG")]
internal void AssertReferencesUninitialized()
{
Debug.Assert(_moduleReferences == null);
}
[Conditional("DEBUG")]
internal void AssertReferencesInitialized()
{
Debug.Assert(_moduleReferences != null);
}
/// <summary>
/// Lookup a top level type referenced from metadata, names should be
/// compared case-sensitively.
/// </summary>
/// <param name="emittedName">
/// Full type name, possibly with generic name mangling.
/// </param>
/// <returns>
/// Symbol for the type, or MissingMetadataSymbol if the type isn't found.
/// </returns>
/// <remarks></remarks>
internal sealed override NamedTypeSymbol LookupTopLevelMetadataType(ref MetadataTypeName emittedName)
{
NamedTypeSymbol result;
NamespaceSymbol scope = this.GlobalNamespace.LookupNestedNamespace(emittedName.NamespaceSegments);
if ((object)scope == null)
{
// We failed to locate the namespace
result = new MissingMetadataTypeSymbol.TopLevel(this, ref emittedName);
}
else
{
result = scope.LookupMetadataType(ref emittedName);
}
Debug.Assert((object)result != null);
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.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
/// <summary>
/// A <see cref="NonMissingModuleSymbol"/> is a special kind of <see cref="ModuleSymbol"/> that represents
/// a module that is not missing, i.e. the "real" thing.
/// </summary>
internal abstract class NonMissingModuleSymbol : ModuleSymbol
{
/// <summary>
/// An array of <see cref="AssemblySymbol"/> objects corresponding to assemblies directly referenced by this module.
/// </summary>
/// <remarks>
/// The contents are provided by ReferenceManager and may not be modified.
/// </remarks>
private ModuleReferences<AssemblySymbol> _moduleReferences;
/// <summary>
/// Does this symbol represent a missing module.
/// </summary>
internal sealed override bool IsMissing
{
get
{
return false;
}
}
/// <summary>
/// Returns an array of assembly identities for assemblies referenced by this module.
/// Items at the same position from GetReferencedAssemblies and from GetReferencedAssemblySymbols
/// should correspond to each other.
/// </summary>
internal sealed override ImmutableArray<AssemblyIdentity> GetReferencedAssemblies()
{
AssertReferencesInitialized();
return _moduleReferences.Identities;
}
/// <summary>
/// Returns an array of AssemblySymbol objects corresponding to assemblies referenced
/// by this module. Items at the same position from GetReferencedAssemblies and
/// from GetReferencedAssemblySymbols should correspond to each other. If reference is
/// not resolved by compiler, GetReferencedAssemblySymbols returns MissingAssemblySymbol in the
/// corresponding item.
/// </summary>
internal sealed override ImmutableArray<AssemblySymbol> GetReferencedAssemblySymbols()
{
AssertReferencesInitialized();
return _moduleReferences.Symbols;
}
internal ImmutableArray<UnifiedAssembly<AssemblySymbol>> GetUnifiedAssemblies()
{
AssertReferencesInitialized();
return _moduleReferences.UnifiedAssemblies;
}
internal override bool HasUnifiedReferences
{
get { return GetUnifiedAssemblies().Length > 0; }
}
internal override bool GetUnificationUseSiteDiagnostic(ref DiagnosticInfo result, TypeSymbol dependentType)
{
AssertReferencesInitialized();
var ownerModule = this;
var ownerAssembly = ownerModule.ContainingAssembly;
var dependentAssembly = dependentType.ContainingAssembly;
if (ownerAssembly == dependentAssembly)
{
return false;
}
// TODO (tomat): we should report an error/warning for all unified references, not just the first one.
foreach (var unifiedAssembly in GetUnifiedAssemblies())
{
if (!ReferenceEquals(unifiedAssembly.TargetAssembly, dependentAssembly))
{
continue;
}
var referenceId = unifiedAssembly.OriginalReference;
var definitionId = dependentAssembly.Identity;
var involvedAssemblies = ImmutableArray.Create<Symbol>(ownerAssembly, dependentAssembly);
DiagnosticInfo info;
if (definitionId.Version > referenceId.Version)
{
// unified with a definition whose version is higher than the reference
ErrorCode warning = (definitionId.Version.Major == referenceId.Version.Major && definitionId.Version.Minor == referenceId.Version.Minor) ?
ErrorCode.WRN_UnifyReferenceBldRev : ErrorCode.WRN_UnifyReferenceMajMin;
// warning: Assuming assembly reference '{0}' used by '{1}' matches identity '{2}' of '{3}', you may need to supply runtime policy.
info = new CSDiagnosticInfo(
warning,
new object[]
{
referenceId.GetDisplayName(),
ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference
definitionId.GetDisplayName(),
dependentAssembly.Name
},
involvedAssemblies,
ImmutableArray<Location>.Empty);
}
else
{
// unified with a definition whose version is lower than the reference
// error: Assembly '{0}' with identity '{1}' uses '{2}' which has a higher version than referenced assembly '{3}' with identity '{4}'
info = new CSDiagnosticInfo(
ErrorCode.ERR_AssemblyMatchBadVersion,
new object[]
{
ownerAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference
ownerAssembly.Identity.GetDisplayName(),
referenceId.GetDisplayName(),
dependentAssembly.Name, // TODO (tomat): should rather be MetadataReference.Display for the corresponding reference
definitionId.GetDisplayName()
},
involvedAssemblies,
ImmutableArray<Location>.Empty);
}
if (MergeUseSiteDiagnostics(ref result, info))
{
return true;
}
}
return false;
}
/// <summary>
/// A helper method for ReferenceManager to set assembly identities for assemblies
/// referenced by this module and corresponding AssemblySymbols.
/// </summary>
internal override void SetReferences(ModuleReferences<AssemblySymbol> moduleReferences, SourceAssemblySymbol originatingSourceAssemblyDebugOnly = null)
{
Debug.Assert(moduleReferences != null);
AssertReferencesUninitialized();
_moduleReferences = moduleReferences;
}
[Conditional("DEBUG")]
internal void AssertReferencesUninitialized()
{
Debug.Assert(_moduleReferences == null);
}
[Conditional("DEBUG")]
internal void AssertReferencesInitialized()
{
Debug.Assert(_moduleReferences != null);
}
/// <summary>
/// Lookup a top level type referenced from metadata, names should be
/// compared case-sensitively.
/// </summary>
/// <param name="emittedName">
/// Full type name, possibly with generic name mangling.
/// </param>
/// <returns>
/// Symbol for the type, or MissingMetadataSymbol if the type isn't found.
/// </returns>
/// <remarks></remarks>
internal sealed override NamedTypeSymbol LookupTopLevelMetadataType(ref MetadataTypeName emittedName)
{
NamedTypeSymbol result;
NamespaceSymbol scope = this.GlobalNamespace.LookupNestedNamespace(emittedName.NamespaceSegments);
if ((object)scope == null)
{
// We failed to locate the namespace
result = new MissingMetadataTypeSymbol.TopLevel(this, ref emittedName);
}
else
{
result = scope.LookupMetadataType(ref emittedName);
}
Debug.Assert((object)result != null);
return result;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/LanguageServices/SymbolDisplayService/AbstractSymbolDisplayService.AnonymousTypes.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.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private void FixAllAnonymousTypes(ISymbol firstSymbol)
{
// First, inline all the delegate anonymous types. This is how VB prefers to display
// things.
InlineAllDelegateAnonymousTypes();
// Now, replace all normal anonymous types with 'a, 'b, etc. and create a
// AnonymousTypes: section to display their info.
FixNormalAnonymousTypes(firstSymbol);
}
private void InlineAllDelegateAnonymousTypes()
{
restart:
foreach (var (group, parts) in _groupMap)
{
var updatedParts = _anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parts, _semanticModel, _position);
if (parts != updatedParts)
{
_groupMap[group] = updatedParts;
goto restart;
}
}
}
private void FixNormalAnonymousTypes(ISymbol firstSymbol)
{
var directNormalAnonymousTypeReferences =
from parts in _groupMap.Values
from part in parts
where part.Symbol.IsNormalAnonymousType()
select (INamedTypeSymbol)part.Symbol;
var info = _anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
firstSymbol, directNormalAnonymousTypeReferences, _semanticModel, _position);
if (info.AnonymousTypesParts.Count > 0)
{
AddToGroup(SymbolDescriptionGroups.AnonymousTypes,
info.AnonymousTypesParts);
restart:
foreach (var (group, parts) in _groupMap)
{
var updatedParts = info.ReplaceAnonymousTypes(parts);
if (parts != updatedParts)
{
_groupMap[group] = updatedParts;
goto restart;
}
}
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal partial class AbstractSymbolDisplayService
{
protected abstract partial class AbstractSymbolDescriptionBuilder
{
private void FixAllAnonymousTypes(ISymbol firstSymbol)
{
// First, inline all the delegate anonymous types. This is how VB prefers to display
// things.
InlineAllDelegateAnonymousTypes();
// Now, replace all normal anonymous types with 'a, 'b, etc. and create a
// AnonymousTypes: section to display their info.
FixNormalAnonymousTypes(firstSymbol);
}
private void InlineAllDelegateAnonymousTypes()
{
restart:
foreach (var (group, parts) in _groupMap)
{
var updatedParts = _anonymousTypeDisplayService.InlineDelegateAnonymousTypes(parts, _semanticModel, _position);
if (parts != updatedParts)
{
_groupMap[group] = updatedParts;
goto restart;
}
}
}
private void FixNormalAnonymousTypes(ISymbol firstSymbol)
{
var directNormalAnonymousTypeReferences =
from parts in _groupMap.Values
from part in parts
where part.Symbol.IsNormalAnonymousType()
select (INamedTypeSymbol)part.Symbol;
var info = _anonymousTypeDisplayService.GetNormalAnonymousTypeDisplayInfo(
firstSymbol, directNormalAnonymousTypeReferences, _semanticModel, _position);
if (info.AnonymousTypesParts.Count > 0)
{
AddToGroup(SymbolDescriptionGroups.AnonymousTypes,
info.AnonymousTypesParts);
restart:
foreach (var (group, parts) in _groupMap)
{
var updatedParts = info.ReplaceAnonymousTypes(parts);
if (parts != updatedParts)
{
_groupMap[group] = updatedParts;
goto restart;
}
}
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Core/ModuleInitializer.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
namespace Roslyn.Test.Utilities
{
internal static class ModuleInitializer
{
[ModuleInitializer]
internal static void Initialize()
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new ThrowingTraceListener());
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis;
namespace Roslyn.Test.Utilities
{
internal static class ModuleInitializer
{
[ModuleInitializer]
internal static void Initialize()
{
Trace.Listeners.Clear();
Trace.Listeners.Add(new ThrowingTraceListener());
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/VisualBasic/LineCommit/AfterCommitCaretMoveUndoPrimitive.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.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Friend Class AfterCommitCaretMoveUndoPrimitive
Inherits AbstractCommitCaretMoveUndoPrimitive
Private ReadOnly _newPosition As Integer
Private ReadOnly _newVirtualSpaces As Integer
Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, position As CaretPosition)
MyBase.New(textBuffer, textBufferAssociatedViewService)
' Grab the old position and virtual spaces. This is cheaper than holding onto
' a VirtualSnapshotPoint as it won't hold old snapshots alive
_newPosition = position.VirtualBufferPosition.Position
_newVirtualSpaces = position.VirtualBufferPosition.VirtualSpaces
End Sub
Public Overrides Sub [Do]()
Dim view = TryGetView()
If view IsNot Nothing Then
view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _newPosition), _newVirtualSpaces))
view.Caret.EnsureVisible()
End If
End Sub
Public Overrides Sub Undo()
' When we are going forward, we do nothing here since the BeforeCommitCaretMoveUndoPrimitive
' will take care of it
End Sub
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.VisualStudio.Text
Imports Microsoft.VisualStudio.Text.Editor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit
Friend Class AfterCommitCaretMoveUndoPrimitive
Inherits AbstractCommitCaretMoveUndoPrimitive
Private ReadOnly _newPosition As Integer
Private ReadOnly _newVirtualSpaces As Integer
Public Sub New(textBuffer As ITextBuffer, textBufferAssociatedViewService As ITextBufferAssociatedViewService, position As CaretPosition)
MyBase.New(textBuffer, textBufferAssociatedViewService)
' Grab the old position and virtual spaces. This is cheaper than holding onto
' a VirtualSnapshotPoint as it won't hold old snapshots alive
_newPosition = position.VirtualBufferPosition.Position
_newVirtualSpaces = position.VirtualBufferPosition.VirtualSpaces
End Sub
Public Overrides Sub [Do]()
Dim view = TryGetView()
If view IsNot Nothing Then
view.Caret.MoveTo(New VirtualSnapshotPoint(New SnapshotPoint(view.TextSnapshot, _newPosition), _newVirtualSpaces))
view.Caret.EnsureVisible()
End If
End Sub
Public Overrides Sub Undo()
' When we are going forward, we do nothing here since the BeforeCommitCaretMoveUndoPrimitive
' will take care of it
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Implementation/EditAndContinue/ActiveStatementTaggerProvider.EventSource.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
internal partial class ActiveStatementTaggerProvider
{
private sealed class EventSource : AbstractWorkspaceTrackingTaggerEventSource
{
public EventSource(ITextBuffer subjectBuffer)
: base(subjectBuffer)
{
}
protected override void ConnectToWorkspace(Workspace workspace)
{
var trackingService = workspace.Services.GetService<IActiveStatementTrackingService>();
if (trackingService != null)
{
trackingService.TrackingChanged += RaiseChanged;
RaiseChanged();
}
}
protected override void DisconnectFromWorkspace(Workspace workspace)
{
var trackingService = workspace.Services.GetService<IActiveStatementTrackingService>();
if (trackingService != null)
{
trackingService.TrackingChanged -= RaiseChanged;
RaiseChanged();
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Shared.Tagging;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.EditAndContinue
{
internal partial class ActiveStatementTaggerProvider
{
private sealed class EventSource : AbstractWorkspaceTrackingTaggerEventSource
{
public EventSource(ITextBuffer subjectBuffer)
: base(subjectBuffer)
{
}
protected override void ConnectToWorkspace(Workspace workspace)
{
var trackingService = workspace.Services.GetService<IActiveStatementTrackingService>();
if (trackingService != null)
{
trackingService.TrackingChanged += RaiseChanged;
RaiseChanged();
}
}
protected override void DisconnectFromWorkspace(Workspace workspace)
{
var trackingService = workspace.Services.GetService<IActiveStatementTrackingService>();
if (trackingService != null)
{
trackingService.TrackingChanged -= RaiseChanged;
RaiseChanged();
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/Implementation/PickMembers/PickMembersDialog.xaml.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
/// <summary>
/// Interaction logic for ExtractInterfaceDialog.xaml
/// </summary>
internal partial class PickMembersDialog : DialogWindow
{
private readonly PickMembersDialogViewModel _viewModel;
// Expose localized strings for binding
public string PickMembersDialogTitle => ServicesVSResources.Pick_members;
public string PickMembersTitle { get; }
public string SelectAll => ServicesVSResources.Select_All;
public string DeselectAll => ServicesVSResources.Deselect_All;
public string OK => ServicesVSResources.OK;
public string Cancel => ServicesVSResources.Cancel;
internal PickMembersDialog(PickMembersDialogViewModel viewModel, string title)
{
PickMembersTitle = title;
_viewModel = viewModel;
SetCommandBindings();
InitializeComponent();
DataContext = viewModel;
}
private void SetCommandBindings()
{
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectAllClickCommand",
typeof(PickMembersDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.S, ModifierKeys.Alt) })),
Select_All_Click));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"DeselectAllClickCommand",
typeof(PickMembersDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.D, ModifierKeys.Alt) })),
Deselect_All_Click));
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
_viewModel.Filter(SearchTextBox.Text);
Members.Items.Refresh();
}
private void OK_Click(object sender, RoutedEventArgs e)
=> DialogResult = true;
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
private void Select_All_Click(object sender, RoutedEventArgs e)
=> _viewModel.SelectAll();
private void Deselect_All_Click(object sender, RoutedEventArgs e)
=> _viewModel.DeselectAll();
private void MoveUp_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveUp && oldSelectedIndex >= 0)
{
_viewModel.MoveUp();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex - 1;
}
SetFocusToSelectedRow();
}
private void MoveDown_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveDown && oldSelectedIndex >= 0)
{
_viewModel.MoveDown();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex + 1;
}
SetFocusToSelectedRow();
}
private void SetFocusToSelectedRow()
{
if (Members.SelectedIndex >= 0)
{
if (!(Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is ListViewItem row))
{
Members.ScrollIntoView(Members.SelectedItem);
row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as ListViewItem;
}
row?.Focus();
}
}
private void OnListViewPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None)
{
ToggleCheckSelection();
e.Handled = true;
}
}
private void OnListViewDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
ToggleCheckSelection();
e.Handled = true;
}
}
private void ToggleCheckSelection()
{
var selectedItems = Members.SelectedItems.OfType<PickMembersDialogViewModel.MemberSymbolViewModel>().ToArray();
var allChecked = selectedItems.All(m => m.IsChecked);
foreach (var item in selectedItems)
{
item.IsChecked = !allChecked;
}
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly PickMembersDialog _dialog;
public TestAccessor(PickMembersDialog dialog)
=> _dialog = dialog;
public Button OKButton => _dialog.OKButton;
public Button CancelButton => _dialog.CancelButton;
public DialogButton UpButton => _dialog.UpButton;
public DialogButton DownButton => _dialog.DownButton;
public AutomationDelegatingListView Members => _dialog.Members;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.PlatformUI;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PickMembers
{
/// <summary>
/// Interaction logic for ExtractInterfaceDialog.xaml
/// </summary>
internal partial class PickMembersDialog : DialogWindow
{
private readonly PickMembersDialogViewModel _viewModel;
// Expose localized strings for binding
public string PickMembersDialogTitle => ServicesVSResources.Pick_members;
public string PickMembersTitle { get; }
public string SelectAll => ServicesVSResources.Select_All;
public string DeselectAll => ServicesVSResources.Deselect_All;
public string OK => ServicesVSResources.OK;
public string Cancel => ServicesVSResources.Cancel;
internal PickMembersDialog(PickMembersDialogViewModel viewModel, string title)
{
PickMembersTitle = title;
_viewModel = viewModel;
SetCommandBindings();
InitializeComponent();
DataContext = viewModel;
}
private void SetCommandBindings()
{
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"SelectAllClickCommand",
typeof(PickMembersDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.S, ModifierKeys.Alt) })),
Select_All_Click));
CommandBindings.Add(new CommandBinding(
new RoutedCommand(
"DeselectAllClickCommand",
typeof(PickMembersDialog),
new InputGestureCollection(new List<InputGesture> { new KeyGesture(Key.D, ModifierKeys.Alt) })),
Deselect_All_Click));
}
private void SearchTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
_viewModel.Filter(SearchTextBox.Text);
Members.Items.Refresh();
}
private void OK_Click(object sender, RoutedEventArgs e)
=> DialogResult = true;
private void Cancel_Click(object sender, RoutedEventArgs e)
=> DialogResult = false;
private void Select_All_Click(object sender, RoutedEventArgs e)
=> _viewModel.SelectAll();
private void Deselect_All_Click(object sender, RoutedEventArgs e)
=> _viewModel.DeselectAll();
private void MoveUp_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveUp && oldSelectedIndex >= 0)
{
_viewModel.MoveUp();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex - 1;
}
SetFocusToSelectedRow();
}
private void MoveDown_Click(object sender, EventArgs e)
{
var oldSelectedIndex = Members.SelectedIndex;
if (_viewModel.CanMoveDown && oldSelectedIndex >= 0)
{
_viewModel.MoveDown();
Members.Items.Refresh();
Members.SelectedIndex = oldSelectedIndex + 1;
}
SetFocusToSelectedRow();
}
private void SetFocusToSelectedRow()
{
if (Members.SelectedIndex >= 0)
{
if (!(Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) is ListViewItem row))
{
Members.ScrollIntoView(Members.SelectedItem);
row = Members.ItemContainerGenerator.ContainerFromIndex(Members.SelectedIndex) as ListViewItem;
}
row?.Focus();
}
}
private void OnListViewPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space && e.KeyboardDevice.Modifiers == ModifierKeys.None)
{
ToggleCheckSelection();
e.Handled = true;
}
}
private void OnListViewDoubleClick(object sender, MouseButtonEventArgs e)
{
if (e.ChangedButton == MouseButton.Left)
{
ToggleCheckSelection();
e.Handled = true;
}
}
private void ToggleCheckSelection()
{
var selectedItems = Members.SelectedItems.OfType<PickMembersDialogViewModel.MemberSymbolViewModel>().ToArray();
var allChecked = selectedItems.All(m => m.IsChecked);
foreach (var item in selectedItems)
{
item.IsChecked = !allChecked;
}
}
internal TestAccessor GetTestAccessor()
=> new(this);
internal readonly struct TestAccessor
{
private readonly PickMembersDialog _dialog;
public TestAccessor(PickMembersDialog dialog)
=> _dialog = dialog;
public Button OKButton => _dialog.OKButton;
public Button CancelButton => _dialog.CancelButton;
public DialogButton UpButton => _dialog.UpButton;
public DialogButton DownButton => _dialog.DownButton;
public AutomationDelegatingListView Members => _dialog.Members;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Syntax/Parsing/ParserRegressionTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Syntax;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
public class ParserRegressionTests : ParsingTests
{
public ParserRegressionTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular);
}
[Fact]
public void PartialLocationInModifierList()
{
var comp = CreateCompilation(@"
class Program
{
partial abstract class A {}
partial abstract class A {}
partial partial class B {}
partial partial class B {}
partial abstract struct S {}
partial abstract struct S {}
}");
comp.VerifyDiagnostics(
// (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract class A {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5),
// (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract class A {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5),
// (7,13): error CS1525: Invalid expression term 'partial'
// partial partial class B {}
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(7, 13),
// (7,13): error CS1002: ; expected
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(7, 13),
// (8,13): error CS1525: Invalid expression term 'partial'
// partial partial class B {}
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(8, 13),
// (8,13): error CS1002: ; expected
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(8, 13),
// (10,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract struct S {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(10, 5),
// (11,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract struct S {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(11, 5),
// (10,29): error CS0106: The modifier 'abstract' is not valid for this item
// partial abstract struct S {}
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S").WithArguments("abstract").WithLocation(10, 29),
// (8,13): error CS0102: The type 'Program' already contains a definition for ''
// partial partial class B {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("Program", "").WithLocation(8, 13),
// (8,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?)
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(8, 5),
// (7,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?)
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(7, 5));
}
[WorkItem(540005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540005")]
[Fact]
public void c01()
{
var test = @"/// \u2750\uDFC1 = </ @goto </ ascending abstract + ( descending __arglist + descending @if <? @switch + global @long + @orderby \u23DC\u6D71\u5070\u9350 ++ into _\u6105\uE331\u27D0 # join [ + break @extern [ @char << partial | + remove + do @else + @typeof @private +
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540006")]
[Fact]
public void c02()
{
var test = @"internal int TYPES() { break retVal = @while ; __reftype CLASS c = dynamic descending CLASS( % ; on IF xx = module _4ไ |= \u14DB\u0849 <![CDATA[ c => @default $ retVal @assembly += c void .Member & -= ; @typeof
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c03()
{
var test = @"/// </summary> /// <returns></returns> else int OPERATOR @uint $ ) { - static ? operator :: ] @readonly = @on async int? , [ return ] { 1 ! , @property & 3 ! @case % partial += ;/*[] bug*/ // YES [] int % ] endregion var = ]]> @for |= @struct , 3, lock 4 @on % 5 goto } @stackalloc } /*,;*/ int %= i = @fixed ?> int << a base <= 1] default ;
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c04()
{
var test = @"/// </summary> /// <returns></returns> internal do OPERATOR || ) { int?[] a = new int? \u14DB\u0849 [5] { 1, 2, 3, 4, @using } /= /*[] bug*/ // YES [] int[] var = { 1, 2, 3, 4, 5 } $ /*,;*/ int i = ; int)a[1];/*[]*/ i = i <<= @__arglist - i @sbyte * @extern / i % i ++ % i || @checked ^ i;
/*+ - * / % & | ^*/
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c000138()
{
var test = @"int?[] /// a = new int? . @string ] { 1, typeof $ 3, 4, 5 } static ; @partial /*[] bug*/ // YES [] int[] var = { 1, else , 3 </ 4 | 5 };/*,;*/ int i = (int)a @in [ __refvalue ] [ /*[]*/ @readonly = i + i - abstract @typevar * i / @this % i & , i | i ^ unchecked i; in /*+ - * / % & | ^*/ bool b = true & false + | true ^ false readonly ;/*& | ^*/ @unsafe = !b;/*!*/ i = ~i;/*~i*/ b = i < (i -
1 @for ) && (i + 1) > i;/*< && >*/
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c000241()
{
var test = @"/// </summary> /// <returns></returns> const by TYPES ascending / ) $ { @let int @byte @by | 0
;
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c024928()
{
var test = @"/// </summary> /// <returns></returns> internal int OPERATOR() { // int?[ * @method ! new int explicit , [ 5 -- { \uDD48\uEF5C , 2, @ascending , @foreach \uD17B\u21A8 . 5 ; { /*[] bug*/ // YES [] int :: ( <= var /> { @readonly 1 <!-- 2 __makeref ? 3 @descending , 4 @float , 5 } disable ;/*,;*/ int -= _\uAEC4 - ( operator int <<= a => += ] @abstract ; property /*[]*/ i = i double + i - @async - i ' & i ) i & @using # @byte , \u7EE1\u8B45 ;/*+ - * / % & | ^*/ bool b %= = true } fixed | class join ^ ?> true ;/*& | ^*/ b ^= ! @null ;/*!*/ @stackalloc = @in == @default ;/*~i*/ b \ i base < / i - await ) && @into ( new i pragma + 1 @for ) > i _\uE02B\u7325 ; else /*< && >*/ continue @double = _ศฝๆ in ^ 1 internal :: 0;/*? :*/ // YES : i++ ~ /*++*/ _\u560C\uF27E\uB73F -- @sizeof ;/*--*/ b @public = /= enum && params false >> true;/*&& ||*/ i @explicit # @byte >>= await ;/*<<*/ @sbyte = @operator i >> 5;/*>>*/ int @from = i; b >> @protected == ) j && assembly i @const != j "" |= i <= @explicit && @await >= @typeof ;/*= == && != <= >=*/ i @long >>= (int ]]> &= ( /*+=*/ i _ศฝๆ -= i explicit -> /*-=*/ i { i -= /**=*/ if ] ( <<= i @assembly ) 0 . @select ++;
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(2771, "https://github.com/dotnet/roslyn/issues/2771")]
[ConditionalFact(typeof(IsRelease))]
public void TestBinary()
{
CSharpSyntaxTree.ParseText(new RandomizedSourceText());
}
[WorkItem(8200, "https://github.com/dotnet/roslyn/issues/8200")]
[Fact]
public void EolParsing()
{
var code = "\n\r"; // Note, it's not "\r\n"
var tree = CSharpSyntaxTree.ParseText(code);
var lines1 = tree.GetText().Lines.Count; // 3
var textSpan = Text.TextSpan.FromBounds(0, tree.Length);
var fileLinePositionSpan = tree.GetLineSpan(textSpan); // throws ArgumentOutOfRangeException
var endLinePosition = fileLinePositionSpan.EndLinePosition;
var line = endLinePosition.Line;
var lines2 = line + 1;
}
[WorkItem(12197, "https://github.com/dotnet/roslyn/issues/12197")]
[Fact]
public void ThrowInInvocationCompletes()
{
var code = "SomeMethod(throw new Exception())";
SyntaxFactory.ParseExpression(code);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13719")]
public void ReportErrorForIncompleteMember()
{
var test = @"
class A
{
[Obsolete(2l)]
public int
}";
ParseAndValidate(test,
// (6,1): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration
// }
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}").WithLocation(6, 1),
// (4,16): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// [Obsolete(2l)]
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 16)
);
}
[Fact]
[WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")]
public void LexerTooManyBadTokens()
{
var source = new StringBuilder();
for (int i = 0; i <= 200; i++)
{
source.Append(@"\u003C");
}
source.Append(@"\u003E\u003E\u003E\u003E");
var parsedTree = ParseWithRoundTripCheck(source.ToString());
IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics();
Assert.Equal("202", actualErrors.Count().ToString());
Assert.Equal("(1,1201): error CS1056: Unexpected character '\\u003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull));
Assert.Equal("(1,1207): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
[WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")]
public void LexerTooManyBadTokens_LongUnicode()
{
var source = new StringBuilder();
for (int i = 0; i <= 200; i++)
{
source.Append(@"\U0000003C");
}
source.Append(@"\u003E\u003E\u003E\u003E");
var parsedTree = ParseWithRoundTripCheck(source.ToString());
IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics();
Assert.Equal("202", actualErrors.Count().ToString());
Assert.Equal("(1,2001): error CS1056: Unexpected character '\\U0000003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull));
Assert.Equal("(1,2011): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void QualifiedName_01()
{
var source =
@"class Program
{
static void Main()
{
A::B.C<D> x;
}
}";
ParseAndValidate(source);
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "D");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_02()
{
var source =
@"class Program
{
static void Main()
{
A::B.C<D> x,
A::B.C<D> y;
}
}";
ParseAndValidate(source,
// (6,10): error CS1002: ; expected
// A::B.C<D> y;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "::").WithLocation(6, 10),
// (6,10): error CS1001: Identifier expected
// A::B.C<D> y;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(6, 10));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "D");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "D");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_03()
{
var source =
@"class Program
{
static void Main()
{
::A.B<C> x;
}
}";
ParseAndValidate(source,
// (4,6): error CS1001: Identifier expected
// {
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "B");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_04()
{
var source =
@"class Program
{
static void Main()
{
::A.B<C>();
}
}";
ParseAndValidate(source,
// (4,6): error CS1001: Identifier expected
// {
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "B");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_05()
{
var source =
@"class Program
{
static void Main()
{
A<B>::C();
}
}";
ParseAndValidate(source,
// (5,13): error CS1001: Identifier expected
// A<B>::C();
Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(5, 13));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.GreaterThanExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_07()
{
var source =
@"class Program
{
static void Main()
{
A<B>::C d;
}
}";
ParseAndValidate(source,
// (5,13): error CS7000: Unexpected use of an aliased name
// A<B>::C d;
Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithArguments("::").WithLocation(5, 13));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "A");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
N(SyntaxKind.GreaterThanToken);
}
}
M(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
#region "Helpers"
private static new void ParseAndValidate(string text, params DiagnosticDescription[] expectedErrors)
{
var parsedTree = ParseWithRoundTripCheck(text);
var actualErrors = parsedTree.GetDiagnostics();
actualErrors.Verify(expectedErrors);
}
#endregion "Helpers"
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.Syntax;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing
{
public class ParserRegressionTests : ParsingTests
{
public ParserRegressionTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular);
}
[Fact]
public void PartialLocationInModifierList()
{
var comp = CreateCompilation(@"
class Program
{
partial abstract class A {}
partial abstract class A {}
partial partial class B {}
partial partial class B {}
partial abstract struct S {}
partial abstract struct S {}
}");
comp.VerifyDiagnostics(
// (4,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract class A {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(4, 5),
// (5,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract class A {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(5, 5),
// (7,13): error CS1525: Invalid expression term 'partial'
// partial partial class B {}
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(7, 13),
// (7,13): error CS1002: ; expected
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(7, 13),
// (8,13): error CS1525: Invalid expression term 'partial'
// partial partial class B {}
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(8, 13),
// (8,13): error CS1002: ; expected
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(8, 13),
// (10,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract struct S {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(10, 5),
// (11,5): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'record', 'struct', 'interface', or a method return type.
// partial abstract struct S {}
Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(11, 5),
// (10,29): error CS0106: The modifier 'abstract' is not valid for this item
// partial abstract struct S {}
Diagnostic(ErrorCode.ERR_BadMemberFlag, "S").WithArguments("abstract").WithLocation(10, 29),
// (8,13): error CS0102: The type 'Program' already contains a definition for ''
// partial partial class B {}
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("Program", "").WithLocation(8, 13),
// (8,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?)
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(8, 5),
// (7,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?)
// partial partial class B {}
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(7, 5));
}
[WorkItem(540005, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540005")]
[Fact]
public void c01()
{
var test = @"/// \u2750\uDFC1 = </ @goto </ ascending abstract + ( descending __arglist + descending @if <? @switch + global @long + @orderby \u23DC\u6D71\u5070\u9350 ++ into _\u6105\uE331\u27D0 # join [ + break @extern [ @char << partial | + remove + do @else + @typeof @private +
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540006, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540006")]
[Fact]
public void c02()
{
var test = @"internal int TYPES() { break retVal = @while ; __reftype CLASS c = dynamic descending CLASS( % ; on IF xx = module _4ไ |= \u14DB\u0849 <![CDATA[ c => @default $ retVal @assembly += c void .Member & -= ; @typeof
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c03()
{
var test = @"/// </summary> /// <returns></returns> else int OPERATOR @uint $ ) { - static ? operator :: ] @readonly = @on async int? , [ return ] { 1 ! , @property & 3 ! @case % partial += ;/*[] bug*/ // YES [] int % ] endregion var = ]]> @for |= @struct , 3, lock 4 @on % 5 goto } @stackalloc } /*,;*/ int %= i = @fixed ?> int << a base <= 1] default ;
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c04()
{
var test = @"/// </summary> /// <returns></returns> internal do OPERATOR || ) { int?[] a = new int? \u14DB\u0849 [5] { 1, 2, 3, 4, @using } /= /*[] bug*/ // YES [] int[] var = { 1, 2, 3, 4, 5 } $ /*,;*/ int i = ; int)a[1];/*[]*/ i = i <<= @__arglist - i @sbyte * @extern / i % i ++ % i || @checked ^ i;
/*+ - * / % & | ^*/
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c000138()
{
var test = @"int?[] /// a = new int? . @string ] { 1, typeof $ 3, 4, 5 } static ; @partial /*[] bug*/ // YES [] int[] var = { 1, else , 3 </ 4 | 5 };/*,;*/ int i = (int)a @in [ __refvalue ] [ /*[]*/ @readonly = i + i - abstract @typevar * i / @this % i & , i | i ^ unchecked i; in /*+ - * / % & | ^*/ bool b = true & false + | true ^ false readonly ;/*& | ^*/ @unsafe = !b;/*!*/ i = ~i;/*~i*/ b = i < (i -
1 @for ) && (i + 1) > i;/*< && >*/
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c000241()
{
var test = @"/// </summary> /// <returns></returns> const by TYPES ascending / ) $ { @let int @byte @by | 0
;
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(540007, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540007")]
[Fact]
public void c024928()
{
var test = @"/// </summary> /// <returns></returns> internal int OPERATOR() { // int?[ * @method ! new int explicit , [ 5 -- { \uDD48\uEF5C , 2, @ascending , @foreach \uD17B\u21A8 . 5 ; { /*[] bug*/ // YES [] int :: ( <= var /> { @readonly 1 <!-- 2 __makeref ? 3 @descending , 4 @float , 5 } disable ;/*,;*/ int -= _\uAEC4 - ( operator int <<= a => += ] @abstract ; property /*[]*/ i = i double + i - @async - i ' & i ) i & @using # @byte , \u7EE1\u8B45 ;/*+ - * / % & | ^*/ bool b %= = true } fixed | class join ^ ?> true ;/*& | ^*/ b ^= ! @null ;/*!*/ @stackalloc = @in == @default ;/*~i*/ b \ i base < / i - await ) && @into ( new i pragma + 1 @for ) > i _\uE02B\u7325 ; else /*< && >*/ continue @double = _ศฝๆ in ^ 1 internal :: 0;/*? :*/ // YES : i++ ~ /*++*/ _\u560C\uF27E\uB73F -- @sizeof ;/*--*/ b @public = /= enum && params false >> true;/*&& ||*/ i @explicit # @byte >>= await ;/*<<*/ @sbyte = @operator i >> 5;/*>>*/ int @from = i; b >> @protected == ) j && assembly i @const != j "" |= i <= @explicit && @await >= @typeof ;/*= == && != <= >=*/ i @long >>= (int ]]> &= ( /*+=*/ i _ศฝๆ -= i explicit -> /*-=*/ i { i -= /**=*/ if ] ( <<= i @assembly ) 0 . @select ++;
";
var tree = SyntaxFactory.ParseSyntaxTree(test);
}
[WorkItem(2771, "https://github.com/dotnet/roslyn/issues/2771")]
[ConditionalFact(typeof(IsRelease))]
public void TestBinary()
{
CSharpSyntaxTree.ParseText(new RandomizedSourceText());
}
[WorkItem(8200, "https://github.com/dotnet/roslyn/issues/8200")]
[Fact]
public void EolParsing()
{
var code = "\n\r"; // Note, it's not "\r\n"
var tree = CSharpSyntaxTree.ParseText(code);
var lines1 = tree.GetText().Lines.Count; // 3
var textSpan = Text.TextSpan.FromBounds(0, tree.Length);
var fileLinePositionSpan = tree.GetLineSpan(textSpan); // throws ArgumentOutOfRangeException
var endLinePosition = fileLinePositionSpan.EndLinePosition;
var line = endLinePosition.Line;
var lines2 = line + 1;
}
[WorkItem(12197, "https://github.com/dotnet/roslyn/issues/12197")]
[Fact]
public void ThrowInInvocationCompletes()
{
var code = "SomeMethod(throw new Exception())";
SyntaxFactory.ParseExpression(code);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/13719")]
public void ReportErrorForIncompleteMember()
{
var test = @"
class A
{
[Obsolete(2l)]
public int
}";
ParseAndValidate(test,
// (6,1): error CS1519: Invalid token '}' in class, record, struct, or interface member declaration
// }
Diagnostic(ErrorCode.ERR_InvalidMemberDecl, "}").WithArguments("}").WithLocation(6, 1),
// (4,16): warning CS0078: The 'l' suffix is easily confused with the digit '1' -- use 'L' for clarity
// [Obsolete(2l)]
Diagnostic(ErrorCode.WRN_LowercaseEllSuffix, "l").WithLocation(4, 16)
);
}
[Fact]
[WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")]
public void LexerTooManyBadTokens()
{
var source = new StringBuilder();
for (int i = 0; i <= 200; i++)
{
source.Append(@"\u003C");
}
source.Append(@"\u003E\u003E\u003E\u003E");
var parsedTree = ParseWithRoundTripCheck(source.ToString());
IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics();
Assert.Equal("202", actualErrors.Count().ToString());
Assert.Equal("(1,1201): error CS1056: Unexpected character '\\u003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull));
Assert.Equal("(1,1207): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
[WorkItem(217398, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=217398")]
public void LexerTooManyBadTokens_LongUnicode()
{
var source = new StringBuilder();
for (int i = 0; i <= 200; i++)
{
source.Append(@"\U0000003C");
}
source.Append(@"\u003E\u003E\u003E\u003E");
var parsedTree = ParseWithRoundTripCheck(source.ToString());
IEnumerable<Diagnostic> actualErrors = parsedTree.GetDiagnostics();
Assert.Equal("202", actualErrors.Count().ToString());
Assert.Equal("(1,2001): error CS1056: Unexpected character '\\U0000003C'", actualErrors.ElementAt(200).ToString(EnsureEnglishUICulture.PreferredOrNull));
Assert.Equal("(1,2011): error CS1056: Unexpected character '\\u003E\\u003E\\u003E\\u003E'", actualErrors.ElementAt(201).ToString(EnsureEnglishUICulture.PreferredOrNull));
}
[Fact]
public void QualifiedName_01()
{
var source =
@"class Program
{
static void Main()
{
A::B.C<D> x;
}
}";
ParseAndValidate(source);
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "D");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_02()
{
var source =
@"class Program
{
static void Main()
{
A::B.C<D> x,
A::B.C<D> y;
}
}";
ParseAndValidate(source,
// (6,10): error CS1002: ; expected
// A::B.C<D> y;
Diagnostic(ErrorCode.ERR_SemicolonExpected, "::").WithLocation(6, 10),
// (6,10): error CS1001: Identifier expected
// A::B.C<D> y;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(6, 10));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "D");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "D");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "y");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_03()
{
var source =
@"class Program
{
static void Main()
{
::A.B<C> x;
}
}";
ParseAndValidate(source,
// (4,6): error CS1001: Identifier expected
// {
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "B");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "x");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_04()
{
var source =
@"class Program
{
static void Main()
{
::A.B<C>();
}
}";
ParseAndValidate(source,
// (4,6): error CS1001: Identifier expected
// {
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(4, 6));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
}
N(SyntaxKind.DotToken);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "B");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_05()
{
var source =
@"class Program
{
static void Main()
{
A<B>::C();
}
}";
ParseAndValidate(source,
// (5,13): error CS1001: Identifier expected
// A<B>::C();
Diagnostic(ErrorCode.ERR_IdentifierExpected, "::").WithLocation(5, 13));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.GreaterThanExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "A");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
}
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.AliasQualifiedName);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.ColonColonToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void QualifiedName_07()
{
var source =
@"class Program
{
static void Main()
{
A<B>::C d;
}
}";
ParseAndValidate(source,
// (5,13): error CS7000: Unexpected use of an aliased name
// A<B>::C d;
Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "::").WithArguments("::").WithLocation(5, 13));
UsingTree(source);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "Program");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.StaticKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "Main");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "A");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "B");
}
N(SyntaxKind.GreaterThanToken);
}
}
M(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "d");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
#region "Helpers"
private static new void ParseAndValidate(string text, params DiagnosticDescription[] expectedErrors)
{
var parsedTree = ParseWithRoundTripCheck(text);
var actualErrors = parsedTree.GetDiagnostics();
actualErrors.Verify(expectedErrors);
}
#endregion "Helpers"
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/CodeRefactorings/ICodeRefactoringService.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.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal interface ICodeRefactoringService
{
Task<bool> HasRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(Document document, TextSpan textSpan, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken);
}
internal static class ICodeRefactoringServiceExtensions
{
public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, CancellationToken cancellationToken)
=> service.GetRefactoringsAsync(document, state, isBlocking: false, cancellationToken);
public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, bool isBlocking, CancellationToken cancellationToken)
=> service.GetRefactoringsAsync(document, state, isBlocking, addOperationScope: _ => null, cancellationToken);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings
{
internal interface ICodeRefactoringService
{
Task<bool> HasRefactoringsAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(Document document, TextSpan textSpan, bool isBlocking, Func<string, IDisposable?> addOperationScope, CancellationToken cancellationToken);
}
internal static class ICodeRefactoringServiceExtensions
{
public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, CancellationToken cancellationToken)
=> service.GetRefactoringsAsync(document, state, isBlocking: false, cancellationToken);
public static Task<ImmutableArray<CodeRefactoring>> GetRefactoringsAsync(this ICodeRefactoringService service, Document document, TextSpan state, bool isBlocking, CancellationToken cancellationToken)
=> service.GetRefactoringsAsync(document, state, isBlocking, addOperationScope: _ => null, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/CodeFixes/Suppression/AbstractSuppressionCodeFixProvider.RemoveSuppressionCodeAction.BatchFixer.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.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider
{
internal abstract partial class RemoveSuppressionCodeAction
{
public static FixAllProvider GetBatchFixer(AbstractSuppressionCodeFixProvider suppressionFixProvider)
=> new RemoveSuppressionBatchFixAllProvider(suppressionFixProvider);
/// <summary>
/// Batch fixer for pragma suppression removal code action.
/// </summary>
private sealed class RemoveSuppressionBatchFixAllProvider : AbstractSuppressionBatchFixAllProvider
{
private readonly AbstractSuppressionCodeFixProvider _suppressionFixProvider;
public RemoveSuppressionBatchFixAllProvider(AbstractSuppressionCodeFixProvider suppressionFixProvider)
=> _suppressionFixProvider = suppressionFixProvider;
protected override async Task AddDocumentFixesAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
// Batch all the pragma remove suppression fixes by executing them sequentially for the document.
var pragmaActionsBuilder = ArrayBuilder<IPragmaBasedCodeAction>.GetInstance();
var pragmaDiagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && d.IsSuppressed))
{
var span = diagnostic.Location.SourceSpan;
var removeSuppressionFixes = await _suppressionFixProvider.GetFixesAsync(
document, span, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
var removeSuppressionFix = removeSuppressionFixes.SingleOrDefault();
if (removeSuppressionFix != null)
{
if (removeSuppressionFix.Action is RemoveSuppressionCodeAction codeAction)
{
if (fixAllState.IsFixMultiple)
{
codeAction = codeAction.CloneForFixMultipleContext();
}
if (codeAction is PragmaRemoveAction pragmaRemoveAction)
{
pragmaActionsBuilder.Add(pragmaRemoveAction);
pragmaDiagnosticsBuilder.Add(diagnostic);
}
else
{
fixes.Add((diagnostic, codeAction));
}
}
}
}
// Get the pragma batch fix.
if (pragmaActionsBuilder.Count > 0)
{
var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix(
_suppressionFixProvider, document,
pragmaActionsBuilder.ToImmutableAndFree(),
pragmaDiagnosticsBuilder.ToImmutableAndFree(),
fixAllState, cancellationToken);
fixes.Add((diagnostic: null, pragmaBatchFix));
}
}
protected override async Task AddProjectFixesAsync(
Project project, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> bag,
FixAllState fixAllState, CancellationToken cancellationToken)
{
foreach (var diagnostic in diagnostics.Where(d => !d.Location.IsInSource && d.IsSuppressed))
{
var removeSuppressionFixes = await _suppressionFixProvider.GetFixesAsync(
project, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
if (removeSuppressionFixes.SingleOrDefault()?.Action is RemoveSuppressionCodeAction removeSuppressionCodeAction)
{
if (fixAllState.IsFixMultiple)
{
removeSuppressionCodeAction = removeSuppressionCodeAction.CloneForFixMultipleContext();
}
bag.Add((diagnostic, removeSuppressionCodeAction));
}
}
}
public override async Task<CodeAction> TryGetMergedFixAsync(
ImmutableArray<(Diagnostic diagnostic, CodeAction action)> batchOfFixes,
FixAllState fixAllState,
CancellationToken cancellationToken)
{
// Batch all the attribute removal fixes into a single fix.
// Pragma removal fixes have already been batch for each document AddDocumentFixes method.
// This ensures no merge conflicts in merging all fixes by our base implementation.
var oldSolution = fixAllState.Project.Solution;
var currentSolution = oldSolution;
var attributeRemoveFixes = new List<AttributeRemoveAction>();
var newBatchOfFixes = new List<(Diagnostic diagnostic, CodeAction action)>();
foreach (var codeAction in batchOfFixes)
{
if (codeAction.action is AttributeRemoveAction attributeRemoveFix)
{
attributeRemoveFixes.Add(attributeRemoveFix);
}
else
{
newBatchOfFixes.Add(codeAction);
}
}
if (attributeRemoveFixes.Count > 0)
{
// Batch all of attribute removal fixes.
foreach (var removeSuppressionFixesForTree in attributeRemoveFixes.GroupBy(fix => fix.SyntaxTreeToModify))
{
var tree = removeSuppressionFixesForTree.Key;
var attributeRemoveFixesForTree = removeSuppressionFixesForTree.OfType<AttributeRemoveAction>().ToImmutableArray();
var attributesToRemove = await GetAttributeNodesToFixAsync(attributeRemoveFixesForTree, cancellationToken).ConfigureAwait(false);
var document = oldSolution.GetDocument(tree);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.RemoveNodes(attributesToRemove, SyntaxRemoveOptions.KeepLeadingTrivia | SyntaxRemoveOptions.AddElasticMarker);
currentSolution = currentSolution.WithDocumentSyntaxRoot(document.Id, newRoot);
}
// This is a temporary generated code action, which doesn't need telemetry, hence suppressing RS0005.
#pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction
var batchAttributeRemoveFix = CodeAction.Create(
attributeRemoveFixes.First().Title,
createChangedSolution: ct => Task.FromResult(currentSolution),
equivalenceKey: fixAllState.CodeActionEquivalenceKey);
#pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction
newBatchOfFixes.Insert(0, (diagnostic: null, batchAttributeRemoveFix));
}
return await base.TryGetMergedFixAsync(
newBatchOfFixes.ToImmutableArray(), fixAllState, cancellationToken).ConfigureAwait(false);
}
private static async Task<ImmutableArray<SyntaxNode>> GetAttributeNodesToFixAsync(ImmutableArray<AttributeRemoveAction> attributeRemoveFixes, CancellationToken cancellationToken)
{
using var builderDisposer = ArrayBuilder<SyntaxNode>.GetInstance(attributeRemoveFixes.Length, out var builder);
foreach (var attributeRemoveFix in attributeRemoveFixes)
{
var attributeToRemove = await attributeRemoveFix.GetAttributeToRemoveAsync(cancellationToken).ConfigureAwait(false);
builder.Add(attributeToRemove);
}
return builder.ToImmutable();
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes.Suppression
{
internal abstract partial class AbstractSuppressionCodeFixProvider : IConfigurationFixProvider
{
internal abstract partial class RemoveSuppressionCodeAction
{
public static FixAllProvider GetBatchFixer(AbstractSuppressionCodeFixProvider suppressionFixProvider)
=> new RemoveSuppressionBatchFixAllProvider(suppressionFixProvider);
/// <summary>
/// Batch fixer for pragma suppression removal code action.
/// </summary>
private sealed class RemoveSuppressionBatchFixAllProvider : AbstractSuppressionBatchFixAllProvider
{
private readonly AbstractSuppressionCodeFixProvider _suppressionFixProvider;
public RemoveSuppressionBatchFixAllProvider(AbstractSuppressionCodeFixProvider suppressionFixProvider)
=> _suppressionFixProvider = suppressionFixProvider;
protected override async Task AddDocumentFixesAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> fixes,
FixAllState fixAllState, CancellationToken cancellationToken)
{
// Batch all the pragma remove suppression fixes by executing them sequentially for the document.
var pragmaActionsBuilder = ArrayBuilder<IPragmaBasedCodeAction>.GetInstance();
var pragmaDiagnosticsBuilder = ArrayBuilder<Diagnostic>.GetInstance();
foreach (var diagnostic in diagnostics.Where(d => d.Location.IsInSource && d.IsSuppressed))
{
var span = diagnostic.Location.SourceSpan;
var removeSuppressionFixes = await _suppressionFixProvider.GetFixesAsync(
document, span, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
var removeSuppressionFix = removeSuppressionFixes.SingleOrDefault();
if (removeSuppressionFix != null)
{
if (removeSuppressionFix.Action is RemoveSuppressionCodeAction codeAction)
{
if (fixAllState.IsFixMultiple)
{
codeAction = codeAction.CloneForFixMultipleContext();
}
if (codeAction is PragmaRemoveAction pragmaRemoveAction)
{
pragmaActionsBuilder.Add(pragmaRemoveAction);
pragmaDiagnosticsBuilder.Add(diagnostic);
}
else
{
fixes.Add((diagnostic, codeAction));
}
}
}
}
// Get the pragma batch fix.
if (pragmaActionsBuilder.Count > 0)
{
var pragmaBatchFix = PragmaBatchFixHelpers.CreateBatchPragmaFix(
_suppressionFixProvider, document,
pragmaActionsBuilder.ToImmutableAndFree(),
pragmaDiagnosticsBuilder.ToImmutableAndFree(),
fixAllState, cancellationToken);
fixes.Add((diagnostic: null, pragmaBatchFix));
}
}
protected override async Task AddProjectFixesAsync(
Project project, ImmutableArray<Diagnostic> diagnostics,
ConcurrentBag<(Diagnostic diagnostic, CodeAction action)> bag,
FixAllState fixAllState, CancellationToken cancellationToken)
{
foreach (var diagnostic in diagnostics.Where(d => !d.Location.IsInSource && d.IsSuppressed))
{
var removeSuppressionFixes = await _suppressionFixProvider.GetFixesAsync(
project, SpecializedCollections.SingletonEnumerable(diagnostic), cancellationToken).ConfigureAwait(false);
if (removeSuppressionFixes.SingleOrDefault()?.Action is RemoveSuppressionCodeAction removeSuppressionCodeAction)
{
if (fixAllState.IsFixMultiple)
{
removeSuppressionCodeAction = removeSuppressionCodeAction.CloneForFixMultipleContext();
}
bag.Add((diagnostic, removeSuppressionCodeAction));
}
}
}
public override async Task<CodeAction> TryGetMergedFixAsync(
ImmutableArray<(Diagnostic diagnostic, CodeAction action)> batchOfFixes,
FixAllState fixAllState,
CancellationToken cancellationToken)
{
// Batch all the attribute removal fixes into a single fix.
// Pragma removal fixes have already been batch for each document AddDocumentFixes method.
// This ensures no merge conflicts in merging all fixes by our base implementation.
var oldSolution = fixAllState.Project.Solution;
var currentSolution = oldSolution;
var attributeRemoveFixes = new List<AttributeRemoveAction>();
var newBatchOfFixes = new List<(Diagnostic diagnostic, CodeAction action)>();
foreach (var codeAction in batchOfFixes)
{
if (codeAction.action is AttributeRemoveAction attributeRemoveFix)
{
attributeRemoveFixes.Add(attributeRemoveFix);
}
else
{
newBatchOfFixes.Add(codeAction);
}
}
if (attributeRemoveFixes.Count > 0)
{
// Batch all of attribute removal fixes.
foreach (var removeSuppressionFixesForTree in attributeRemoveFixes.GroupBy(fix => fix.SyntaxTreeToModify))
{
var tree = removeSuppressionFixesForTree.Key;
var attributeRemoveFixesForTree = removeSuppressionFixesForTree.OfType<AttributeRemoveAction>().ToImmutableArray();
var attributesToRemove = await GetAttributeNodesToFixAsync(attributeRemoveFixesForTree, cancellationToken).ConfigureAwait(false);
var document = oldSolution.GetDocument(tree);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = root.RemoveNodes(attributesToRemove, SyntaxRemoveOptions.KeepLeadingTrivia | SyntaxRemoveOptions.AddElasticMarker);
currentSolution = currentSolution.WithDocumentSyntaxRoot(document.Id, newRoot);
}
// This is a temporary generated code action, which doesn't need telemetry, hence suppressing RS0005.
#pragma warning disable RS0005 // Do not use generic CodeAction.Create to create CodeAction
var batchAttributeRemoveFix = CodeAction.Create(
attributeRemoveFixes.First().Title,
createChangedSolution: ct => Task.FromResult(currentSolution),
equivalenceKey: fixAllState.CodeActionEquivalenceKey);
#pragma warning restore RS0005 // Do not use generic CodeAction.Create to create CodeAction
newBatchOfFixes.Insert(0, (diagnostic: null, batchAttributeRemoveFix));
}
return await base.TryGetMergedFixAsync(
newBatchOfFixes.ToImmutableArray(), fixAllState, cancellationToken).ConfigureAwait(false);
}
private static async Task<ImmutableArray<SyntaxNode>> GetAttributeNodesToFixAsync(ImmutableArray<AttributeRemoveAction> attributeRemoveFixes, CancellationToken cancellationToken)
{
using var builderDisposer = ArrayBuilder<SyntaxNode>.GetInstance(attributeRemoveFixes.Length, out var builder);
foreach (var attributeRemoveFix in attributeRemoveFixes)
{
var attributeToRemove = await attributeRemoveFix.GetAttributeToRemoveAsync(cancellationToken).ConfigureAwait(false);
builder.Add(attributeToRemove);
}
return builder.ToImmutable();
}
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/Operations/CaptureId.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Capture Id is an opaque identifier to represent an intermediate result from an <see cref="IFlowCaptureOperation"/>.
/// </summary>
public struct CaptureId : IEquatable<CaptureId>
{
internal CaptureId(int value)
{
Debug.Assert(value >= 0);
Value = value;
}
internal int Value { get; }
/// <summary>
/// Compares <see cref="CaptureId"/>s.
/// </summary>
public bool Equals(CaptureId other) => Value == other.Value;
/// <inheritdoc/>
public override bool Equals(object? obj) => obj is CaptureId && Equals((CaptureId)obj);
/// <inheritdoc/>
public override int GetHashCode() => Value.GetHashCode();
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Diagnostics;
namespace Microsoft.CodeAnalysis.FlowAnalysis
{
/// <summary>
/// Capture Id is an opaque identifier to represent an intermediate result from an <see cref="IFlowCaptureOperation"/>.
/// </summary>
public struct CaptureId : IEquatable<CaptureId>
{
internal CaptureId(int value)
{
Debug.Assert(value >= 0);
Value = value;
}
internal int Value { get; }
/// <summary>
/// Compares <see cref="CaptureId"/>s.
/// </summary>
public bool Equals(CaptureId other) => Value == other.Value;
/// <inheritdoc/>
public override bool Equals(object? obj) => obj is CaptureId && Equals((CaptureId)obj);
/// <inheritdoc/>
public override int GetHashCode() => Value.GetHashCode();
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Remote/Core/Serialization/RoslynJsonConverter.RoslynOnly.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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.TodoComments;
using Newtonsoft.Json;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class AggregateJsonConverter : JsonConverter
{
#pragma warning disable CA1822 // Mark members as static
// this type is shared by multiple teams such as Razor, LUT and etc which have either
// separated/shared/shim repo so some types might not available to those context. this
// partial method let us add Roslyn specific types without breaking them
partial void AppendRoslynSpecificJsonConverters(ImmutableDictionary<Type, JsonConverter>.Builder builder)
#pragma warning restore CA1822 // Mark members as static
{
Add(builder, new HighlightSpanJsonConverter());
Add(builder, new TaggedTextJsonConverter());
Add(builder, new TodoCommentDescriptorJsonConverter());
Add(builder, new TodoCommentJsonConverter());
Add(builder, new AnalyzerPerformanceInfoConverter());
}
private class TodoCommentDescriptorJsonConverter : BaseJsonConverter<TodoCommentDescriptor>
{
protected override TodoCommentDescriptor ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var text = ReadProperty<string>(reader);
var priority = ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TodoCommentDescriptor(text, (int)priority);
}
protected override void WriteValue(JsonWriter writer, TodoCommentDescriptor descriptor, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("text");
writer.WriteValue(descriptor.Text);
writer.WritePropertyName("priority");
writer.WriteValue(descriptor.Priority);
writer.WriteEndObject();
}
}
private class TodoCommentJsonConverter : BaseJsonConverter<TodoComment>
{
protected override TodoComment ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var descriptor = ReadProperty<TodoCommentDescriptor>(reader, serializer);
var message = ReadProperty<string>(reader);
var position = ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TodoComment(descriptor, message, (int)position);
}
protected override void WriteValue(JsonWriter writer, TodoComment todoComment, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TodoComment.Descriptor));
serializer.Serialize(writer, todoComment.Descriptor);
writer.WritePropertyName(nameof(TodoComment.Message));
writer.WriteValue(todoComment.Message);
writer.WritePropertyName(nameof(TodoComment.Position));
writer.WriteValue(todoComment.Position);
writer.WriteEndObject();
}
}
private class HighlightSpanJsonConverter : BaseJsonConverter<HighlightSpan>
{
protected override HighlightSpan ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
var textSpan = ReadProperty<TextSpan>(reader, serializer);
var kind = (HighlightSpanKind)ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new HighlightSpan(textSpan, kind);
}
protected override void WriteValue(JsonWriter writer, HighlightSpan source, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(HighlightSpan.TextSpan));
serializer.Serialize(writer, source.TextSpan);
writer.WritePropertyName(nameof(HighlightSpan.Kind));
writer.WriteValue(source.Kind);
writer.WriteEndObject();
}
}
private class TaggedTextJsonConverter : BaseJsonConverter<TaggedText>
{
protected override TaggedText ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
var tag = ReadProperty<string>(reader);
var text = ReadProperty<string>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TaggedText(tag, text);
}
protected override void WriteValue(JsonWriter writer, TaggedText source, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TaggedText.Tag));
writer.WriteValue(source.Tag);
writer.WritePropertyName(nameof(TaggedText.Text));
writer.WriteValue(source.Text);
writer.WriteEndObject();
}
}
private class AnalyzerPerformanceInfoConverter : BaseJsonConverter<AnalyzerPerformanceInfo>
{
protected override AnalyzerPerformanceInfo ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
var analyzerid = ReadProperty<string>(reader);
var builtIn = ReadProperty<bool>(reader);
var timeSpan = ReadProperty<TimeSpan>(reader, serializer);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new AnalyzerPerformanceInfo(analyzerid, builtIn, timeSpan);
}
protected override void WriteValue(JsonWriter writer, AnalyzerPerformanceInfo info, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(AnalyzerPerformanceInfo.AnalyzerId));
writer.WriteValue(info.AnalyzerId);
writer.WritePropertyName(nameof(AnalyzerPerformanceInfo.BuiltIn));
writer.WriteValue(info.BuiltIn);
writer.WritePropertyName(nameof(AnalyzerPerformanceInfo.TimeSpan));
serializer.Serialize(writer, info.TimeSpan);
writer.WriteEndObject();
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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 Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.DocumentHighlighting;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.TodoComments;
using Newtonsoft.Json;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Remote
{
internal partial class AggregateJsonConverter : JsonConverter
{
#pragma warning disable CA1822 // Mark members as static
// this type is shared by multiple teams such as Razor, LUT and etc which have either
// separated/shared/shim repo so some types might not available to those context. this
// partial method let us add Roslyn specific types without breaking them
partial void AppendRoslynSpecificJsonConverters(ImmutableDictionary<Type, JsonConverter>.Builder builder)
#pragma warning restore CA1822 // Mark members as static
{
Add(builder, new HighlightSpanJsonConverter());
Add(builder, new TaggedTextJsonConverter());
Add(builder, new TodoCommentDescriptorJsonConverter());
Add(builder, new TodoCommentJsonConverter());
Add(builder, new AnalyzerPerformanceInfoConverter());
}
private class TodoCommentDescriptorJsonConverter : BaseJsonConverter<TodoCommentDescriptor>
{
protected override TodoCommentDescriptor ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var text = ReadProperty<string>(reader);
var priority = ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TodoCommentDescriptor(text, (int)priority);
}
protected override void WriteValue(JsonWriter writer, TodoCommentDescriptor descriptor, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName("text");
writer.WriteValue(descriptor.Text);
writer.WritePropertyName("priority");
writer.WriteValue(descriptor.Priority);
writer.WriteEndObject();
}
}
private class TodoCommentJsonConverter : BaseJsonConverter<TodoComment>
{
protected override TodoComment ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
// all integer is long
var descriptor = ReadProperty<TodoCommentDescriptor>(reader, serializer);
var message = ReadProperty<string>(reader);
var position = ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TodoComment(descriptor, message, (int)position);
}
protected override void WriteValue(JsonWriter writer, TodoComment todoComment, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TodoComment.Descriptor));
serializer.Serialize(writer, todoComment.Descriptor);
writer.WritePropertyName(nameof(TodoComment.Message));
writer.WriteValue(todoComment.Message);
writer.WritePropertyName(nameof(TodoComment.Position));
writer.WriteValue(todoComment.Position);
writer.WriteEndObject();
}
}
private class HighlightSpanJsonConverter : BaseJsonConverter<HighlightSpan>
{
protected override HighlightSpan ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
var textSpan = ReadProperty<TextSpan>(reader, serializer);
var kind = (HighlightSpanKind)ReadProperty<long>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new HighlightSpan(textSpan, kind);
}
protected override void WriteValue(JsonWriter writer, HighlightSpan source, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(HighlightSpan.TextSpan));
serializer.Serialize(writer, source.TextSpan);
writer.WritePropertyName(nameof(HighlightSpan.Kind));
writer.WriteValue(source.Kind);
writer.WriteEndObject();
}
}
private class TaggedTextJsonConverter : BaseJsonConverter<TaggedText>
{
protected override TaggedText ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
var tag = ReadProperty<string>(reader);
var text = ReadProperty<string>(reader);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new TaggedText(tag, text);
}
protected override void WriteValue(JsonWriter writer, TaggedText source, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(TaggedText.Tag));
writer.WriteValue(source.Tag);
writer.WritePropertyName(nameof(TaggedText.Text));
writer.WriteValue(source.Text);
writer.WriteEndObject();
}
}
private class AnalyzerPerformanceInfoConverter : BaseJsonConverter<AnalyzerPerformanceInfo>
{
protected override AnalyzerPerformanceInfo ReadValue(JsonReader reader, JsonSerializer serializer)
{
Contract.ThrowIfFalse(reader.TokenType == JsonToken.StartObject);
var analyzerid = ReadProperty<string>(reader);
var builtIn = ReadProperty<bool>(reader);
var timeSpan = ReadProperty<TimeSpan>(reader, serializer);
Contract.ThrowIfFalse(reader.Read());
Contract.ThrowIfFalse(reader.TokenType == JsonToken.EndObject);
return new AnalyzerPerformanceInfo(analyzerid, builtIn, timeSpan);
}
protected override void WriteValue(JsonWriter writer, AnalyzerPerformanceInfo info, JsonSerializer serializer)
{
writer.WriteStartObject();
writer.WritePropertyName(nameof(AnalyzerPerformanceInfo.AnalyzerId));
writer.WriteValue(info.AnalyzerId);
writer.WritePropertyName(nameof(AnalyzerPerformanceInfo.BuiltIn));
writer.WriteValue(info.BuiltIn);
writer.WritePropertyName(nameof(AnalyzerPerformanceInfo.TimeSpan));
serializer.Serialize(writer, info.TimeSpan);
writer.WriteEndObject();
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/ExternalAccess/Razor/IRazorDocumentOperationService.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal interface IRazorDocumentOperationService
{
/// <summary>
/// document version of <see cref="Workspace.CanApplyChange(ApplyChangesKind)"/>
/// </summary>
bool CanApplyChange { get; }
/// <summary>
/// indicates whether this document supports diagnostics or not
/// </summary>
bool SupportDiagnostics { 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.
namespace Microsoft.CodeAnalysis.ExternalAccess.Razor
{
internal interface IRazorDocumentOperationService
{
/// <summary>
/// document version of <see cref="Workspace.CanApplyChange(ApplyChangesKind)"/>
/// </summary>
bool CanApplyChange { get; }
/// <summary>
/// indicates whether this document supports diagnostics or not
/// </summary>
bool SupportDiagnostics { get; }
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/QuickInfo/CommonSemanticQuickInfoProvider.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.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.QuickInfo
{
internal abstract partial class CommonSemanticQuickInfoProvider : CommonQuickInfoProvider
{
protected override async Task<QuickInfoItem?> BuildQuickInfoAsync(
QuickInfoContext context, SyntaxToken token)
{
var (tokenInformation, supportedPlatforms) = await ComputeQuickInfoDataAsync(context, token).ConfigureAwait(false);
if (tokenInformation.Symbols.IsDefaultOrEmpty)
return null;
var cancellationToken = context.CancellationToken;
var semanticModel = await context.Document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await CreateContentAsync(
context.Document.Project.Solution.Workspace, semanticModel, token, tokenInformation, supportedPlatforms, cancellationToken).ConfigureAwait(false);
}
protected override async Task<QuickInfoItem?> BuildQuickInfoAsync(
CommonQuickInfoContext context, SyntaxToken token)
{
var tokenInformation = BindToken(context.Workspace, context.SemanticModel, token, context.CancellationToken);
if (tokenInformation.Symbols.IsDefaultOrEmpty)
return null;
return await CreateContentAsync(
context.Workspace, context.SemanticModel, token, tokenInformation, supportedPlatforms: null, context.CancellationToken).ConfigureAwait(false);
}
private async Task<(TokenInformation tokenInformation, SupportedPlatformData? supportedPlatforms)> ComputeQuickInfoDataAsync(
QuickInfoContext context,
SyntaxToken token)
{
var cancellationToken = context.CancellationToken;
var document = context.Document;
var linkedDocumentIds = document.GetLinkedDocumentIds();
if (linkedDocumentIds.Any())
return await ComputeFromLinkedDocumentsAsync(context, token, linkedDocumentIds).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var tokenInformation = BindToken(
document.Project.Solution.Workspace, semanticModel, token, cancellationToken);
return (tokenInformation, supportedPlatforms: null);
}
private async Task<(TokenInformation, SupportedPlatformData supportedPlatforms)> ComputeFromLinkedDocumentsAsync(
QuickInfoContext context,
SyntaxToken token,
ImmutableArray<DocumentId> linkedDocumentIds)
{
// Linked files/shared projects: imagine the following when GOO is false
// #if GOO
// int x = 3;
// #endif
// var y = x$$;
//
// 'x' will bind as an error type, so we'll show incorrect information.
// Instead, we need to find the head in which we get the best binding,
// which in this case is the one with no errors.
var cancellationToken = context.CancellationToken;
var document = context.Document;
var solution = document.Project.Solution;
var workspace = solution.Workspace;
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var mainTokenInformation = BindToken(workspace, semanticModel, token, cancellationToken);
var candidateProjects = new List<ProjectId> { document.Project.Id };
var invalidProjects = new List<ProjectId>();
var candidateResults = new List<(DocumentId docId, TokenInformation tokenInformation)>
{
(document.Id, mainTokenInformation)
};
foreach (var linkedDocumentId in linkedDocumentIds)
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
var linkedModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var linkedToken = FindTokenInLinkedDocument(token, linkedModel, cancellationToken);
if (linkedToken != default)
{
// Not in an inactive region, so this file is a candidate.
candidateProjects.Add(linkedDocumentId.ProjectId);
var linkedSymbols = BindToken(workspace, linkedModel, linkedToken, cancellationToken);
candidateResults.Add((linkedDocumentId, linkedSymbols));
}
}
// Take the first result with no errors.
// If every file binds with errors, take the first candidate, which is from the current file.
var bestBinding = candidateResults.FirstOrNull(c => HasNoErrors(c.tokenInformation.Symbols))
?? candidateResults.First();
if (bestBinding.tokenInformation.Symbols.IsDefaultOrEmpty)
return default;
// We calculate the set of supported projects
candidateResults.Remove(bestBinding);
foreach (var (docId, tokenInformation) in candidateResults)
{
// Does the candidate have anything remotely equivalent?
if (!tokenInformation.Symbols.Intersect(bestBinding.tokenInformation.Symbols, LinkedFilesSymbolEquivalenceComparer.Instance).Any())
invalidProjects.Add(docId.ProjectId);
}
var supportedPlatforms = new SupportedPlatformData(invalidProjects, candidateProjects, workspace);
return (bestBinding.tokenInformation, supportedPlatforms);
}
private static bool HasNoErrors(ImmutableArray<ISymbol> symbols)
=> symbols.Length > 0
&& !ErrorVisitor.ContainsError(symbols.FirstOrDefault());
private static SyntaxToken FindTokenInLinkedDocument(
SyntaxToken token,
SemanticModel linkedModel,
CancellationToken cancellationToken)
{
var root = linkedModel.SyntaxTree.GetRoot(cancellationToken);
if (root == null)
return default;
// Don't search trivia because we want to ignore inactive regions
var linkedToken = root.FindToken(token.SpanStart);
// The new and old tokens should have the same span?
return token.Span == linkedToken.Span ? linkedToken : default;
}
protected static Task<QuickInfoItem> CreateContentAsync(
Workspace workspace,
SemanticModel semanticModel,
SyntaxToken token,
TokenInformation tokenInformation,
SupportedPlatformData? supportedPlatforms,
CancellationToken cancellationToken)
{
var syntaxFactsService = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>();
var symbols = tokenInformation.Symbols;
// if generating quick info for an attribute, prefer bind to the class instead of the constructor
if (syntaxFactsService.IsAttributeName(token.Parent!))
{
symbols = symbols.OrderBy((s1, s2) =>
s1.Kind == s2.Kind ? 0 :
s1.Kind == SymbolKind.NamedType ? -1 :
s2.Kind == SymbolKind.NamedType ? 1 : 0).ToImmutableArray();
}
return QuickInfoUtilities.CreateQuickInfoItemAsync(
workspace, semanticModel, token.Span, symbols, supportedPlatforms,
tokenInformation.ShowAwaitReturn, tokenInformation.NullableFlowState, cancellationToken);
}
protected abstract bool GetBindableNodeForTokenIndicatingLambda(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found);
protected abstract bool GetBindableNodeForTokenIndicatingPossibleIndexerAccess(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found);
protected virtual NullableFlowState GetNullabilityAnalysis(Workspace workspace, SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => NullableFlowState.None;
private TokenInformation BindToken(
Workspace workspace, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
{
var hostServices = workspace.Services;
var languageServices = hostServices.GetLanguageServices(semanticModel.Language);
var syntaxFacts = languageServices.GetRequiredService<ISyntaxFactsService>();
var enclosingType = semanticModel.GetEnclosingNamedType(token.SpanStart, cancellationToken);
var symbols = GetSymbolsFromToken(token, workspace, semanticModel, cancellationToken);
var bindableParent = syntaxFacts.TryGetBindableParent(token);
var overloads = bindableParent != null
? semanticModel.GetMemberGroup(bindableParent, cancellationToken)
: ImmutableArray<ISymbol>.Empty;
symbols = symbols.Where(IsOk)
.Where(s => IsAccessible(s, enclosingType))
.Concat(overloads)
.Distinct(SymbolEquivalenceComparer.Instance)
.ToImmutableArray();
if (symbols.Any())
{
var firstSymbol = symbols.First();
var isAwait = syntaxFacts.IsAwaitKeyword(token);
var nullableFlowState = NullableFlowState.None;
if (bindableParent != null)
{
nullableFlowState = GetNullabilityAnalysis(workspace, semanticModel, firstSymbol, bindableParent, cancellationToken);
}
return new TokenInformation(symbols, isAwait, nullableFlowState);
}
// Couldn't bind the token to specific symbols. If it's an operator, see if we can at
// least bind it to a type.
if (syntaxFacts.IsOperator(token))
{
var typeInfo = semanticModel.GetTypeInfo(token.Parent!, cancellationToken);
if (IsOk(typeInfo.Type))
{
return new TokenInformation(ImmutableArray.Create<ISymbol>(typeInfo.Type));
}
}
return new TokenInformation(ImmutableArray<ISymbol>.Empty);
}
private ImmutableArray<ISymbol> GetSymbolsFromToken(SyntaxToken token, Workspace workspace, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (GetBindableNodeForTokenIndicatingLambda(token, out var lambdaSyntax))
{
var symbol = semanticModel.GetSymbolInfo(lambdaSyntax, cancellationToken).Symbol;
return symbol != null ? ImmutableArray.Create(symbol) : ImmutableArray<ISymbol>.Empty;
}
if (GetBindableNodeForTokenIndicatingPossibleIndexerAccess(token, out var elementAccessExpression))
{
var symbol = semanticModel.GetSymbolInfo(elementAccessExpression, cancellationToken).Symbol;
if (symbol?.IsIndexer() == true)
{
return ImmutableArray.Create(symbol);
}
}
return semanticModel.GetSemanticInfo(token, workspace, cancellationToken)
.GetSymbols(includeType: true);
}
private static bool IsOk([NotNullWhen(returnValue: true)] ISymbol? symbol)
{
if (symbol == null)
return false;
if (symbol.IsErrorType())
return false;
if (symbol is ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Cref })
return false;
return true;
}
private static bool IsAccessible(ISymbol symbol, INamedTypeSymbol? within)
=> within == null
|| symbol.IsAccessibleWithin(within);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// 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.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Collections;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.QuickInfo
{
internal abstract partial class CommonSemanticQuickInfoProvider : CommonQuickInfoProvider
{
protected override async Task<QuickInfoItem?> BuildQuickInfoAsync(
QuickInfoContext context, SyntaxToken token)
{
var (tokenInformation, supportedPlatforms) = await ComputeQuickInfoDataAsync(context, token).ConfigureAwait(false);
if (tokenInformation.Symbols.IsDefaultOrEmpty)
return null;
var cancellationToken = context.CancellationToken;
var semanticModel = await context.Document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
return await CreateContentAsync(
context.Document.Project.Solution.Workspace, semanticModel, token, tokenInformation, supportedPlatforms, cancellationToken).ConfigureAwait(false);
}
protected override async Task<QuickInfoItem?> BuildQuickInfoAsync(
CommonQuickInfoContext context, SyntaxToken token)
{
var tokenInformation = BindToken(context.Workspace, context.SemanticModel, token, context.CancellationToken);
if (tokenInformation.Symbols.IsDefaultOrEmpty)
return null;
return await CreateContentAsync(
context.Workspace, context.SemanticModel, token, tokenInformation, supportedPlatforms: null, context.CancellationToken).ConfigureAwait(false);
}
private async Task<(TokenInformation tokenInformation, SupportedPlatformData? supportedPlatforms)> ComputeQuickInfoDataAsync(
QuickInfoContext context,
SyntaxToken token)
{
var cancellationToken = context.CancellationToken;
var document = context.Document;
var linkedDocumentIds = document.GetLinkedDocumentIds();
if (linkedDocumentIds.Any())
return await ComputeFromLinkedDocumentsAsync(context, token, linkedDocumentIds).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var tokenInformation = BindToken(
document.Project.Solution.Workspace, semanticModel, token, cancellationToken);
return (tokenInformation, supportedPlatforms: null);
}
private async Task<(TokenInformation, SupportedPlatformData supportedPlatforms)> ComputeFromLinkedDocumentsAsync(
QuickInfoContext context,
SyntaxToken token,
ImmutableArray<DocumentId> linkedDocumentIds)
{
// Linked files/shared projects: imagine the following when GOO is false
// #if GOO
// int x = 3;
// #endif
// var y = x$$;
//
// 'x' will bind as an error type, so we'll show incorrect information.
// Instead, we need to find the head in which we get the best binding,
// which in this case is the one with no errors.
var cancellationToken = context.CancellationToken;
var document = context.Document;
var solution = document.Project.Solution;
var workspace = solution.Workspace;
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var mainTokenInformation = BindToken(workspace, semanticModel, token, cancellationToken);
var candidateProjects = new List<ProjectId> { document.Project.Id };
var invalidProjects = new List<ProjectId>();
var candidateResults = new List<(DocumentId docId, TokenInformation tokenInformation)>
{
(document.Id, mainTokenInformation)
};
foreach (var linkedDocumentId in linkedDocumentIds)
{
var linkedDocument = solution.GetRequiredDocument(linkedDocumentId);
var linkedModel = await linkedDocument.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var linkedToken = FindTokenInLinkedDocument(token, linkedModel, cancellationToken);
if (linkedToken != default)
{
// Not in an inactive region, so this file is a candidate.
candidateProjects.Add(linkedDocumentId.ProjectId);
var linkedSymbols = BindToken(workspace, linkedModel, linkedToken, cancellationToken);
candidateResults.Add((linkedDocumentId, linkedSymbols));
}
}
// Take the first result with no errors.
// If every file binds with errors, take the first candidate, which is from the current file.
var bestBinding = candidateResults.FirstOrNull(c => HasNoErrors(c.tokenInformation.Symbols))
?? candidateResults.First();
if (bestBinding.tokenInformation.Symbols.IsDefaultOrEmpty)
return default;
// We calculate the set of supported projects
candidateResults.Remove(bestBinding);
foreach (var (docId, tokenInformation) in candidateResults)
{
// Does the candidate have anything remotely equivalent?
if (!tokenInformation.Symbols.Intersect(bestBinding.tokenInformation.Symbols, LinkedFilesSymbolEquivalenceComparer.Instance).Any())
invalidProjects.Add(docId.ProjectId);
}
var supportedPlatforms = new SupportedPlatformData(invalidProjects, candidateProjects, workspace);
return (bestBinding.tokenInformation, supportedPlatforms);
}
private static bool HasNoErrors(ImmutableArray<ISymbol> symbols)
=> symbols.Length > 0
&& !ErrorVisitor.ContainsError(symbols.FirstOrDefault());
private static SyntaxToken FindTokenInLinkedDocument(
SyntaxToken token,
SemanticModel linkedModel,
CancellationToken cancellationToken)
{
var root = linkedModel.SyntaxTree.GetRoot(cancellationToken);
if (root == null)
return default;
// Don't search trivia because we want to ignore inactive regions
var linkedToken = root.FindToken(token.SpanStart);
// The new and old tokens should have the same span?
return token.Span == linkedToken.Span ? linkedToken : default;
}
protected static Task<QuickInfoItem> CreateContentAsync(
Workspace workspace,
SemanticModel semanticModel,
SyntaxToken token,
TokenInformation tokenInformation,
SupportedPlatformData? supportedPlatforms,
CancellationToken cancellationToken)
{
var syntaxFactsService = workspace.Services.GetLanguageServices(semanticModel.Language).GetRequiredService<ISyntaxFactsService>();
var symbols = tokenInformation.Symbols;
// if generating quick info for an attribute, prefer bind to the class instead of the constructor
if (syntaxFactsService.IsAttributeName(token.Parent!))
{
symbols = symbols.OrderBy((s1, s2) =>
s1.Kind == s2.Kind ? 0 :
s1.Kind == SymbolKind.NamedType ? -1 :
s2.Kind == SymbolKind.NamedType ? 1 : 0).ToImmutableArray();
}
return QuickInfoUtilities.CreateQuickInfoItemAsync(
workspace, semanticModel, token.Span, symbols, supportedPlatforms,
tokenInformation.ShowAwaitReturn, tokenInformation.NullableFlowState, cancellationToken);
}
protected abstract bool GetBindableNodeForTokenIndicatingLambda(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found);
protected abstract bool GetBindableNodeForTokenIndicatingPossibleIndexerAccess(SyntaxToken token, [NotNullWhen(returnValue: true)] out SyntaxNode? found);
protected virtual NullableFlowState GetNullabilityAnalysis(Workspace workspace, SemanticModel semanticModel, ISymbol symbol, SyntaxNode node, CancellationToken cancellationToken) => NullableFlowState.None;
private TokenInformation BindToken(
Workspace workspace, SemanticModel semanticModel, SyntaxToken token, CancellationToken cancellationToken)
{
var hostServices = workspace.Services;
var languageServices = hostServices.GetLanguageServices(semanticModel.Language);
var syntaxFacts = languageServices.GetRequiredService<ISyntaxFactsService>();
var enclosingType = semanticModel.GetEnclosingNamedType(token.SpanStart, cancellationToken);
var symbols = GetSymbolsFromToken(token, workspace, semanticModel, cancellationToken);
var bindableParent = syntaxFacts.TryGetBindableParent(token);
var overloads = bindableParent != null
? semanticModel.GetMemberGroup(bindableParent, cancellationToken)
: ImmutableArray<ISymbol>.Empty;
symbols = symbols.Where(IsOk)
.Where(s => IsAccessible(s, enclosingType))
.Concat(overloads)
.Distinct(SymbolEquivalenceComparer.Instance)
.ToImmutableArray();
if (symbols.Any())
{
var firstSymbol = symbols.First();
var isAwait = syntaxFacts.IsAwaitKeyword(token);
var nullableFlowState = NullableFlowState.None;
if (bindableParent != null)
{
nullableFlowState = GetNullabilityAnalysis(workspace, semanticModel, firstSymbol, bindableParent, cancellationToken);
}
return new TokenInformation(symbols, isAwait, nullableFlowState);
}
// Couldn't bind the token to specific symbols. If it's an operator, see if we can at
// least bind it to a type.
if (syntaxFacts.IsOperator(token))
{
var typeInfo = semanticModel.GetTypeInfo(token.Parent!, cancellationToken);
if (IsOk(typeInfo.Type))
{
return new TokenInformation(ImmutableArray.Create<ISymbol>(typeInfo.Type));
}
}
return new TokenInformation(ImmutableArray<ISymbol>.Empty);
}
private ImmutableArray<ISymbol> GetSymbolsFromToken(SyntaxToken token, Workspace workspace, SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (GetBindableNodeForTokenIndicatingLambda(token, out var lambdaSyntax))
{
var symbol = semanticModel.GetSymbolInfo(lambdaSyntax, cancellationToken).Symbol;
return symbol != null ? ImmutableArray.Create(symbol) : ImmutableArray<ISymbol>.Empty;
}
if (GetBindableNodeForTokenIndicatingPossibleIndexerAccess(token, out var elementAccessExpression))
{
var symbol = semanticModel.GetSymbolInfo(elementAccessExpression, cancellationToken).Symbol;
if (symbol?.IsIndexer() == true)
{
return ImmutableArray.Create(symbol);
}
}
return semanticModel.GetSemanticInfo(token, workspace, cancellationToken)
.GetSymbols(includeType: true);
}
private static bool IsOk([NotNullWhen(returnValue: true)] ISymbol? symbol)
{
if (symbol == null)
return false;
if (symbol.IsErrorType())
return false;
if (symbol is ITypeParameterSymbol { TypeParameterKind: TypeParameterKind.Cref })
return false;
return true;
}
private static bool IsAccessible(ISymbol symbol, INamedTypeSymbol? within)
=> within == null
|| symbol.IsAccessibleWithin(within);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Analyzers/CSharp/Analyzers/UseImplicitOrExplicitType/CSharpUseImplicitTypeDiagnosticAnalyzer.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseImplicitTypeDiagnosticAnalyzer : CSharpTypeStyleDiagnosticAnalyzerBase
{
private static readonly LocalizableString s_Title =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_implicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
private static readonly LocalizableString s_Message =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.use_var_instead_of_explicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
protected override CSharpTypeStyleHelper Helper => CSharpUseImplicitTypeHelper.Instance;
public CSharpUseImplicitTypeDiagnosticAnalyzer()
: base(diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId,
enforceOnBuild: EnforceOnBuildValues.UseImplicitType,
title: s_Title,
message: s_Message)
{
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Diagnostics;
namespace Microsoft.CodeAnalysis.CSharp.Diagnostics.TypeStyle
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
internal sealed class CSharpUseImplicitTypeDiagnosticAnalyzer : CSharpTypeStyleDiagnosticAnalyzerBase
{
private static readonly LocalizableString s_Title =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.Use_implicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
private static readonly LocalizableString s_Message =
new LocalizableResourceString(nameof(CSharpAnalyzersResources.use_var_instead_of_explicit_type), CSharpAnalyzersResources.ResourceManager, typeof(CSharpAnalyzersResources));
protected override CSharpTypeStyleHelper Helper => CSharpUseImplicitTypeHelper.Instance;
public CSharpUseImplicitTypeDiagnosticAnalyzer()
: base(diagnosticId: IDEDiagnosticIds.UseImplicitTypeDiagnosticId,
enforceOnBuild: EnforceOnBuildValues.UseImplicitType,
title: s_Title,
message: s_Message)
{
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Lowering/AsyncRewriter/AsyncRewriter.AsyncMethodToClassRewriter.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class AsyncRewriter
Inherits StateMachineRewriter(Of CapturedSymbolOrExpression)
Partial Friend Class AsyncMethodToClassRewriter
Inherits StateMachineMethodToClassRewriter
''' <summary>
''' The method being rewritten.
''' </summary>
Private ReadOnly _method As MethodSymbol
''' <summary>
''' The field of the generated async class used to store the async method builder: an instance of
''' AsyncVoidMethodBuilder, AsyncTaskMethodBuilder, or AsyncTaskMethodBuilder(Of T) depending on the
''' return type of the async method.
''' </summary>
Private ReadOnly _builder As FieldSymbol
''' <summary>
''' The exprReturnLabel is used to label the return handling code at the end of the async state-machine
''' method. Return expressions are rewritten as unconditional branches to exprReturnLabel.
''' </summary>
Private ReadOnly _exprReturnLabel As LabelSymbol
''' <summary>
''' The exitLabel is used to label the final method body return at the end of the async state-machine
''' method. Is used in rewriting of return statements from Await expressions and a couple of other
''' places where the return is not accompanied by return of the value.
''' </summary>
Private ReadOnly _exitLabel As LabelSymbol
''' <summary>
''' The field of the generated async class used in generic task returning async methods to store the value
''' of rewritten return expressions. The return-handling code then uses SetResult on the async method builder
''' to make the result available to the caller.
''' </summary>
Private ReadOnly _exprRetValue As LocalSymbol = Nothing
Private ReadOnly _asyncMethodKind As AsyncMethodKind
Private ReadOnly _awaiterFields As New Dictionary(Of TypeSymbol, FieldSymbol)()
Private _nextAwaiterId As Integer
Private ReadOnly _owner As AsyncRewriter
Private ReadOnly _spillFieldAllocator As SpillFieldAllocator
Private ReadOnly _typesNeedingClearingCache As New Dictionary(Of TypeSymbol, Boolean)
Friend Sub New(method As MethodSymbol,
F As SyntheticBoundNodeFactory,
state As FieldSymbol,
builder As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
nonReusableLocalProxies As Dictionary(Of Symbol, CapturedSymbolOrExpression),
synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
owner As AsyncRewriter,
diagnostics As BindingDiagnosticBag)
MyBase.New(F, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics)
Me._method = method
Me._builder = builder
Me._exprReturnLabel = F.GenerateLabel("exprReturn")
Me._exitLabel = F.GenerateLabel("exitLabel")
Me._owner = owner
Me._asyncMethodKind = GetAsyncMethodKind(Me._method)
Me._spillFieldAllocator = New SpillFieldAllocator(F)
If Me._asyncMethodKind = AsyncMethodKind.GenericTaskFunction Then
Me._exprRetValue = Me.F.SynthesizedLocal(Me._owner._resultType, SynthesizedLocalKind.StateMachineReturnValue, F.Syntax)
End If
Me._nextAwaiterId = If(slotAllocatorOpt IsNot Nothing, slotAllocatorOpt.PreviousAwaiterSlotCount, 0)
End Sub
Private Function GetAwaiterField(awaiterType As TypeSymbol) As FieldSymbol
Dim result As FieldSymbol = Nothing
' Awaiters of the same type always share the same slot, regardless of what await expressions they belong to.
' Even in case of nested await expressions only one awaiter Is active.
' So we don't need to tie the awaiter variable to a particular await expression and only use its type
' to find the previous awaiter field.
If Not Me._awaiterFields.TryGetValue(awaiterType, result) Then
Dim slotIndex As Integer = -1
If Me.SlotAllocatorOpt Is Nothing OrElse Not Me.SlotAllocatorOpt.TryGetPreviousAwaiterSlotIndex(F.CompilationState.ModuleBuilderOpt.Translate(awaiterType, F.Syntax, F.Diagnostics.DiagnosticBag), F.Diagnostics.DiagnosticBag, slotIndex) Then
slotIndex = _nextAwaiterId
_nextAwaiterId = _nextAwaiterId + 1
End If
Dim fieldName As String = GeneratedNames.MakeStateMachineAwaiterFieldName(slotIndex)
result = Me.F.StateMachineField(awaiterType, Me._method, fieldName, SynthesizedLocalKind.AwaiterField, slotIndex, accessibility:=Accessibility.Friend)
Me._awaiterFields.Add(awaiterType, result)
End If
Return result
End Function
''' <summary>
''' Generate the body for MoveNext()
''' </summary>
Friend Sub GenerateMoveNext(body As BoundStatement, moveNextMethod As MethodSymbol)
Me.F.CurrentMethod = moveNextMethod
Dim rewrittenBody As BoundStatement = DirectCast(Visit(body), BoundStatement)
Dim rootScopeHoistedLocals As ImmutableArray(Of FieldSymbol) = Nothing
TryUnwrapBoundStateMachineScope(rewrittenBody, rootScopeHoistedLocals)
Dim bodyBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
' NOTE: We don't need to create/use any label after Dispatch inside Try block below
' NOTE: because 'Case' clauses inside dispatching Select statement map states to
' NOTE: correspondent Await points (or nested Try blocks) and 'NotStartedStateMachine'
' NOTE: falls to the 'Case Else' category and just falls through to the [body] part
' STMT: Try
' STMT: Select Me.$State ' Dispatch
' STMT: Case <state1> ' ...
' STMT: ' ...
' STMT: End Select
' STMT: ' Fall through
' STMT: [body]
' STMT: ...
' STMT: Catch $ex As Exception
' STMT: state = finishedState
' STMT: builder.SetException($ex)
' STMT: Return
' STMT: End Try
' STMT: cachedState = state
bodyBuilder.Add(
Me.F.Assignment(
Me.F.Local(Me.CachedState, True),
Me.F.Field(Me.F.Me(), Me.StateField, False)))
' Note that the first real sequence point comes after the dispatch jump table is because
' the Begin construct should map to the logical beginning of the method. A breakpoint
' there should only be hit once, upon first entry into the method, and subsequent calls
' to MoveNext to resume the method should not hit that breakpoint.
Dim exceptionLocal = Me.F.SynthesizedLocal(Me.F.WellKnownType(WellKnownType.System_Exception))
bodyBuilder.Add(
Me.F.Try(
Me.F.Block(
ImmutableArray(Of LocalSymbol).Empty,
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.Dispatch(),
rewrittenBody
),
Me.F.CatchBlocks(
Me.F.Catch(
exceptionLocal,
Me.F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.F.Assignment(Me.F.Field(Me.F.Me(), Me.StateField, True), Me.F.Literal(StateMachineStates.FinishedStateMachine)),
Me.F.ExpressionStatement(
Me._owner.GenerateMethodCall(
Me.F.Field(Me.F.Me(), Me._builder, False),
Me._owner._builderType,
"SetException",
Me.F.Local(exceptionLocal, False))),
Me.F.Goto(Me._exitLabel)),
isSynthesizedAsyncCatchAll:=True))))
' STMT: ExprReturnLabel: ' for the rewritten 'Return <expressions>' statements in the user's method body
bodyBuilder.Add(Me.F.Label(Me._exprReturnLabel))
' STMT: state = cachedState = finishedState
Dim stateDone = Me.F.Assignment(
Me.F.Field(Me.F.Me(), Me.StateField, True),
Me.F.AssignmentExpression(Me.F.Local(Me.CachedState, True), Me.F.Literal(StateMachineStates.FinishedStateMachine)))
Dim block As MethodBlockSyntax = TryCast(body.Syntax, MethodBlockSyntax)
If (block Is Nothing) Then
bodyBuilder.Add(stateDone)
Else
bodyBuilder.Add(Me.F.SequencePointWithSpan(block, block.EndBlockStatement.Span, stateDone))
bodyBuilder.Add(SyntheticBoundNodeFactory.HiddenSequencePoint())
End If
' STMT: builder.SetResult([RetVal])
bodyBuilder.Add(
Me.F.ExpressionStatement(
Me._owner.GenerateMethodCall(
Me.F.Field(Me.F.Me(), Me._builder, False),
Me._owner._builderType,
"SetResult",
If(Me._asyncMethodKind = AsyncMethodKind.GenericTaskFunction,
{Me.F.Local(Me._exprRetValue, False)}, Array.Empty(Of BoundExpression)()))))
' STMT: ReturnLabel: ' for the forced exit from the method, such as return from catch block above
bodyBuilder.Add(Me.F.Label(Me._exitLabel))
bodyBuilder.Add(Me.F.Return())
Dim newStatements As ImmutableArray(Of BoundStatement) = bodyBuilder.ToImmutableAndFree()
Dim newBody = Me.F.Block(
If(Me._exprRetValue IsNot Nothing,
ImmutableArray.Create(Me._exprRetValue, Me.CachedState),
ImmutableArray.Create(Me.CachedState)),
newStatements)
If rootScopeHoistedLocals.Length > 0 Then
newBody = MakeStateMachineScope(rootScopeHoistedLocals, newBody)
End If
Me._owner.CloseMethod(newBody)
End Sub
Protected Overrides ReadOnly Property ResumeLabelName As String
Get
Return "asyncLabel"
End Get
End Property
Protected Overrides Function GenerateReturn(finished As Boolean) As BoundStatement
Return Me.F.Goto(Me._exitLabel)
End Function
Protected Overrides ReadOnly Property IsInExpressionLambda As Boolean
Get
Return False
End Get
End Property
End Class
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.CodeGen
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend NotInheritable Class AsyncRewriter
Inherits StateMachineRewriter(Of CapturedSymbolOrExpression)
Partial Friend Class AsyncMethodToClassRewriter
Inherits StateMachineMethodToClassRewriter
''' <summary>
''' The method being rewritten.
''' </summary>
Private ReadOnly _method As MethodSymbol
''' <summary>
''' The field of the generated async class used to store the async method builder: an instance of
''' AsyncVoidMethodBuilder, AsyncTaskMethodBuilder, or AsyncTaskMethodBuilder(Of T) depending on the
''' return type of the async method.
''' </summary>
Private ReadOnly _builder As FieldSymbol
''' <summary>
''' The exprReturnLabel is used to label the return handling code at the end of the async state-machine
''' method. Return expressions are rewritten as unconditional branches to exprReturnLabel.
''' </summary>
Private ReadOnly _exprReturnLabel As LabelSymbol
''' <summary>
''' The exitLabel is used to label the final method body return at the end of the async state-machine
''' method. Is used in rewriting of return statements from Await expressions and a couple of other
''' places where the return is not accompanied by return of the value.
''' </summary>
Private ReadOnly _exitLabel As LabelSymbol
''' <summary>
''' The field of the generated async class used in generic task returning async methods to store the value
''' of rewritten return expressions. The return-handling code then uses SetResult on the async method builder
''' to make the result available to the caller.
''' </summary>
Private ReadOnly _exprRetValue As LocalSymbol = Nothing
Private ReadOnly _asyncMethodKind As AsyncMethodKind
Private ReadOnly _awaiterFields As New Dictionary(Of TypeSymbol, FieldSymbol)()
Private _nextAwaiterId As Integer
Private ReadOnly _owner As AsyncRewriter
Private ReadOnly _spillFieldAllocator As SpillFieldAllocator
Private ReadOnly _typesNeedingClearingCache As New Dictionary(Of TypeSymbol, Boolean)
Friend Sub New(method As MethodSymbol,
F As SyntheticBoundNodeFactory,
state As FieldSymbol,
builder As FieldSymbol,
hoistedVariables As IReadOnlySet(Of Symbol),
nonReusableLocalProxies As Dictionary(Of Symbol, CapturedSymbolOrExpression),
synthesizedLocalOrdinals As SynthesizedLocalOrdinalsDispenser,
slotAllocatorOpt As VariableSlotAllocator,
nextFreeHoistedLocalSlot As Integer,
owner As AsyncRewriter,
diagnostics As BindingDiagnosticBag)
MyBase.New(F, state, hoistedVariables, nonReusableLocalProxies, synthesizedLocalOrdinals, slotAllocatorOpt, nextFreeHoistedLocalSlot, diagnostics)
Me._method = method
Me._builder = builder
Me._exprReturnLabel = F.GenerateLabel("exprReturn")
Me._exitLabel = F.GenerateLabel("exitLabel")
Me._owner = owner
Me._asyncMethodKind = GetAsyncMethodKind(Me._method)
Me._spillFieldAllocator = New SpillFieldAllocator(F)
If Me._asyncMethodKind = AsyncMethodKind.GenericTaskFunction Then
Me._exprRetValue = Me.F.SynthesizedLocal(Me._owner._resultType, SynthesizedLocalKind.StateMachineReturnValue, F.Syntax)
End If
Me._nextAwaiterId = If(slotAllocatorOpt IsNot Nothing, slotAllocatorOpt.PreviousAwaiterSlotCount, 0)
End Sub
Private Function GetAwaiterField(awaiterType As TypeSymbol) As FieldSymbol
Dim result As FieldSymbol = Nothing
' Awaiters of the same type always share the same slot, regardless of what await expressions they belong to.
' Even in case of nested await expressions only one awaiter Is active.
' So we don't need to tie the awaiter variable to a particular await expression and only use its type
' to find the previous awaiter field.
If Not Me._awaiterFields.TryGetValue(awaiterType, result) Then
Dim slotIndex As Integer = -1
If Me.SlotAllocatorOpt Is Nothing OrElse Not Me.SlotAllocatorOpt.TryGetPreviousAwaiterSlotIndex(F.CompilationState.ModuleBuilderOpt.Translate(awaiterType, F.Syntax, F.Diagnostics.DiagnosticBag), F.Diagnostics.DiagnosticBag, slotIndex) Then
slotIndex = _nextAwaiterId
_nextAwaiterId = _nextAwaiterId + 1
End If
Dim fieldName As String = GeneratedNames.MakeStateMachineAwaiterFieldName(slotIndex)
result = Me.F.StateMachineField(awaiterType, Me._method, fieldName, SynthesizedLocalKind.AwaiterField, slotIndex, accessibility:=Accessibility.Friend)
Me._awaiterFields.Add(awaiterType, result)
End If
Return result
End Function
''' <summary>
''' Generate the body for MoveNext()
''' </summary>
Friend Sub GenerateMoveNext(body As BoundStatement, moveNextMethod As MethodSymbol)
Me.F.CurrentMethod = moveNextMethod
Dim rewrittenBody As BoundStatement = DirectCast(Visit(body), BoundStatement)
Dim rootScopeHoistedLocals As ImmutableArray(Of FieldSymbol) = Nothing
TryUnwrapBoundStateMachineScope(rewrittenBody, rootScopeHoistedLocals)
Dim bodyBuilder = ArrayBuilder(Of BoundStatement).GetInstance()
' NOTE: We don't need to create/use any label after Dispatch inside Try block below
' NOTE: because 'Case' clauses inside dispatching Select statement map states to
' NOTE: correspondent Await points (or nested Try blocks) and 'NotStartedStateMachine'
' NOTE: falls to the 'Case Else' category and just falls through to the [body] part
' STMT: Try
' STMT: Select Me.$State ' Dispatch
' STMT: Case <state1> ' ...
' STMT: ' ...
' STMT: End Select
' STMT: ' Fall through
' STMT: [body]
' STMT: ...
' STMT: Catch $ex As Exception
' STMT: state = finishedState
' STMT: builder.SetException($ex)
' STMT: Return
' STMT: End Try
' STMT: cachedState = state
bodyBuilder.Add(
Me.F.Assignment(
Me.F.Local(Me.CachedState, True),
Me.F.Field(Me.F.Me(), Me.StateField, False)))
' Note that the first real sequence point comes after the dispatch jump table is because
' the Begin construct should map to the logical beginning of the method. A breakpoint
' there should only be hit once, upon first entry into the method, and subsequent calls
' to MoveNext to resume the method should not hit that breakpoint.
Dim exceptionLocal = Me.F.SynthesizedLocal(Me.F.WellKnownType(WellKnownType.System_Exception))
bodyBuilder.Add(
Me.F.Try(
Me.F.Block(
ImmutableArray(Of LocalSymbol).Empty,
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.Dispatch(),
rewrittenBody
),
Me.F.CatchBlocks(
Me.F.Catch(
exceptionLocal,
Me.F.Block(
SyntheticBoundNodeFactory.HiddenSequencePoint(),
Me.F.Assignment(Me.F.Field(Me.F.Me(), Me.StateField, True), Me.F.Literal(StateMachineStates.FinishedStateMachine)),
Me.F.ExpressionStatement(
Me._owner.GenerateMethodCall(
Me.F.Field(Me.F.Me(), Me._builder, False),
Me._owner._builderType,
"SetException",
Me.F.Local(exceptionLocal, False))),
Me.F.Goto(Me._exitLabel)),
isSynthesizedAsyncCatchAll:=True))))
' STMT: ExprReturnLabel: ' for the rewritten 'Return <expressions>' statements in the user's method body
bodyBuilder.Add(Me.F.Label(Me._exprReturnLabel))
' STMT: state = cachedState = finishedState
Dim stateDone = Me.F.Assignment(
Me.F.Field(Me.F.Me(), Me.StateField, True),
Me.F.AssignmentExpression(Me.F.Local(Me.CachedState, True), Me.F.Literal(StateMachineStates.FinishedStateMachine)))
Dim block As MethodBlockSyntax = TryCast(body.Syntax, MethodBlockSyntax)
If (block Is Nothing) Then
bodyBuilder.Add(stateDone)
Else
bodyBuilder.Add(Me.F.SequencePointWithSpan(block, block.EndBlockStatement.Span, stateDone))
bodyBuilder.Add(SyntheticBoundNodeFactory.HiddenSequencePoint())
End If
' STMT: builder.SetResult([RetVal])
bodyBuilder.Add(
Me.F.ExpressionStatement(
Me._owner.GenerateMethodCall(
Me.F.Field(Me.F.Me(), Me._builder, False),
Me._owner._builderType,
"SetResult",
If(Me._asyncMethodKind = AsyncMethodKind.GenericTaskFunction,
{Me.F.Local(Me._exprRetValue, False)}, Array.Empty(Of BoundExpression)()))))
' STMT: ReturnLabel: ' for the forced exit from the method, such as return from catch block above
bodyBuilder.Add(Me.F.Label(Me._exitLabel))
bodyBuilder.Add(Me.F.Return())
Dim newStatements As ImmutableArray(Of BoundStatement) = bodyBuilder.ToImmutableAndFree()
Dim newBody = Me.F.Block(
If(Me._exprRetValue IsNot Nothing,
ImmutableArray.Create(Me._exprRetValue, Me.CachedState),
ImmutableArray.Create(Me.CachedState)),
newStatements)
If rootScopeHoistedLocals.Length > 0 Then
newBody = MakeStateMachineScope(rootScopeHoistedLocals, newBody)
End If
Me._owner.CloseMethod(newBody)
End Sub
Protected Overrides ReadOnly Property ResumeLabelName As String
Get
Return "asyncLabel"
End Get
End Property
Protected Overrides Function GenerateReturn(finished As Boolean) As BoundStatement
Return Me.F.Goto(Me._exitLabel)
End Function
Protected Overrides ReadOnly Property IsInExpressionLambda As Boolean
Get
Return False
End Get
End Property
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/LanguageServer/Protocol/ILanguageServerFactory.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.VisualStudio.LanguageServer.Protocol;
using StreamJsonRpc;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal interface ILanguageServerFactory
{
public ILanguageServerTarget Create(
JsonRpc jsonRpc,
ICapabilitiesProvider capabilitiesProvider,
ILspWorkspaceRegistrationService workspaceRegistrationService,
ILspLogger logger);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.VisualStudio.LanguageServer.Protocol;
using StreamJsonRpc;
namespace Microsoft.CodeAnalysis.LanguageServer
{
internal interface ILanguageServerFactory
{
public ILanguageServerTarget Create(
JsonRpc jsonRpc,
ICapabilitiesProvider capabilitiesProvider,
ILspWorkspaceRegistrationService workspaceRegistrationService,
ILspLogger logger);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/MSBuild/MSBuild/Build/ProjectBuildManager.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild.Build
{
internal class ProjectBuildManager
{
private static readonly XmlReaderSettings s_xmlReaderSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
};
private static readonly ImmutableDictionary<string, string> s_defaultGlobalProperties = new Dictionary<string, string>()
{
// this will tell msbuild to not build the dependent projects
{ PropertyNames.DesignTimeBuild, bool.TrueString },
// this will force CoreCompile task to execute even if all inputs and outputs are up to date
#if NETCOREAPP
{ PropertyNames.NonExistentFile, "__NonExistentSubDir__\\__NonExistentFile__" },
#else
// Setting `BuildingInsideVisualStudio` indirectly sets NonExistentFile:
// https://github.com/microsoft/msbuild/blob/ab9b2f36a5ff7a85f842b205d5529e77fdc9d7ab/src/Tasks/Microsoft.Common.CurrentVersion.targets#L3462-L3470
{ PropertyNames.BuildingInsideVisualStudio, bool.TrueString },
#endif
{ PropertyNames.BuildProjectReferences, bool.FalseString },
{ PropertyNames.BuildingProject, bool.FalseString },
// retrieve the command-line arguments to the compiler
{ PropertyNames.ProvideCommandLineArgs, bool.TrueString },
// don't actually run the compiler
{ PropertyNames.SkipCompilerExecution, bool.TrueString },
{ PropertyNames.ContinueOnError, PropertyValues.ErrorAndContinue },
// this ensures that the parent project's configuration and platform will be used for
// referenced projects. So, setting Configuration=Release will also cause any project
// references to also be built with Configuration=Release. This is necessary for getting
// a more-likely-to-be-correct output path from project references.
{ PropertyNames.ShouldUnsetParentConfigurationAndPlatform, bool.FalseString }
}.ToImmutableDictionary();
private readonly ImmutableDictionary<string, string> _additionalGlobalProperties;
private readonly ILogger? _msbuildLogger;
private MSB.Evaluation.ProjectCollection? _batchBuildProjectCollection;
private MSBuildDiagnosticLogger? _batchBuildLogger;
~ProjectBuildManager()
{
if (BatchBuildStarted)
{
throw new InvalidOperationException("ProjectBuilderManager.Stop() not called.");
}
}
public ProjectBuildManager(ImmutableDictionary<string, string> additionalGlobalProperties, ILogger? msbuildLogger = null)
{
_additionalGlobalProperties = additionalGlobalProperties ?? ImmutableDictionary<string, string>.Empty;
_msbuildLogger = msbuildLogger;
}
private ImmutableDictionary<string, string> AllGlobalProperties
=> s_defaultGlobalProperties.AddRange(_additionalGlobalProperties);
private static async Task<(MSB.Evaluation.Project? project, DiagnosticLog log)> LoadProjectAsync(
string path, MSB.Evaluation.ProjectCollection? projectCollection, CancellationToken cancellationToken)
{
var log = new DiagnosticLog();
try
{
var loadedProjects = projectCollection?.GetLoadedProjects(path);
if (loadedProjects != null && loadedProjects.Count > 0)
{
Debug.Assert(loadedProjects.Count == 1);
return (loadedProjects.First(), log);
}
using var stream = FileUtilities.OpenAsyncRead(path);
using var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken).ConfigureAwait(false);
using var xmlReader = XmlReader.Create(readStream, s_xmlReaderSettings);
var xml = MSB.Construction.ProjectRootElement.Create(xmlReader, projectCollection);
// When constructing a project from an XmlReader, MSBuild cannot determine the project file path. Setting the
// path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work.
xml.FullPath = path;
var project = new MSB.Evaluation.Project(xml, globalProperties: null, toolsVersion: null, projectCollection);
return (project, log);
}
catch (Exception e)
{
log.Add(e, path);
return (project: null, log);
}
}
public Task<(MSB.Evaluation.Project? project, DiagnosticLog log)> LoadProjectAsync(
string path, CancellationToken cancellationToken)
{
if (BatchBuildStarted)
{
return LoadProjectAsync(path, _batchBuildProjectCollection, cancellationToken);
}
else
{
var projectCollection = new MSB.Evaluation.ProjectCollection(AllGlobalProperties);
try
{
return LoadProjectAsync(path, projectCollection, cancellationToken);
}
finally
{
// unload project so collection will release global strings
projectCollection.UnloadAllProjects();
}
}
}
public async Task<string?> TryGetOutputFilePathAsync(
string path, CancellationToken cancellationToken)
{
Debug.Assert(BatchBuildStarted);
// This tries to get the project output path and retrieving the evaluated $(TargetPath) property.
var (project, _) = await LoadProjectAsync(path, cancellationToken).ConfigureAwait(false);
return project?.GetPropertyValue(PropertyNames.TargetPath);
}
public bool BatchBuildStarted { get; private set; }
public void StartBatchBuild(IDictionary<string, string>? globalProperties = null)
{
if (BatchBuildStarted)
{
throw new InvalidOperationException();
}
globalProperties ??= ImmutableDictionary<string, string>.Empty;
var allProperties = s_defaultGlobalProperties.RemoveRange(globalProperties.Keys).AddRange(globalProperties);
_batchBuildProjectCollection = new MSB.Evaluation.ProjectCollection(allProperties);
_batchBuildLogger = new MSBuildDiagnosticLogger()
{
Verbosity = MSB.Framework.LoggerVerbosity.Normal
};
var buildParameters = new MSB.Execution.BuildParameters(_batchBuildProjectCollection)
{
Loggers = _msbuildLogger is null
? (new MSB.Framework.ILogger[] { _batchBuildLogger })
: (new MSB.Framework.ILogger[] { _batchBuildLogger, _msbuildLogger })
};
MSB.Execution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
BatchBuildStarted = true;
}
public void EndBatchBuild()
{
if (!BatchBuildStarted)
{
throw new InvalidOperationException();
}
MSB.Execution.BuildManager.DefaultBuildManager.EndBuild();
// unload project so collection will release global strings
_batchBuildProjectCollection?.UnloadAllProjects();
_batchBuildProjectCollection = null;
_batchBuildLogger = null;
BatchBuildStarted = false;
}
public Task<MSB.Execution.ProjectInstance> BuildProjectAsync(
MSB.Evaluation.Project project, DiagnosticLog log, CancellationToken cancellationToken)
{
Debug.Assert(BatchBuildStarted);
var targets = new[] { TargetNames.Compile, TargetNames.CoreCompile };
return BuildProjectAsync(project, targets, log, cancellationToken);
}
private async Task<MSB.Execution.ProjectInstance> BuildProjectAsync(
MSB.Evaluation.Project project, string[] targets, DiagnosticLog log, CancellationToken cancellationToken)
{
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var projectInstance = project.CreateProjectInstance();
// Verify targets
foreach (var target in targets)
{
if (!projectInstance.Targets.ContainsKey(target))
{
log.Add(string.Format(WorkspaceMSBuildResources.Project_does_not_contain_0_target, target), projectInstance.FullPath);
return projectInstance;
}
}
_batchBuildLogger?.SetProjectAndLog(projectInstance.FullPath, log);
var buildRequestData = new MSB.Execution.BuildRequestData(projectInstance, targets);
var result = await BuildAsync(buildRequestData, cancellationToken).ConfigureAwait(false);
if (result.OverallResult == MSB.Execution.BuildResultCode.Failure)
{
if (result.Exception != null)
{
log.Add(result.Exception, projectInstance.FullPath);
}
}
return projectInstance;
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly SemaphoreSlim s_buildManagerLock = new(initialCount: 1);
private static async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, requestData, cancellationToken).ConfigureAwait(false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
// enable cancellation of build
CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
// Note: We only ever expect that a single submission is being built,
// even though we're calling CancelAllSubmissions(). If MSBuildWorkspace is
// ever updated to support parallel builds, we'll likely need to update this code.
taskSource.TrySetCanceled();
buildManager.CancelAllSubmissions();
registration.Dispose();
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.CodeAnalysis.MSBuild.Logging;
using Roslyn.Utilities;
using MSB = Microsoft.Build;
namespace Microsoft.CodeAnalysis.MSBuild.Build
{
internal class ProjectBuildManager
{
private static readonly XmlReaderSettings s_xmlReaderSettings = new()
{
DtdProcessing = DtdProcessing.Prohibit,
XmlResolver = null
};
private static readonly ImmutableDictionary<string, string> s_defaultGlobalProperties = new Dictionary<string, string>()
{
// this will tell msbuild to not build the dependent projects
{ PropertyNames.DesignTimeBuild, bool.TrueString },
// this will force CoreCompile task to execute even if all inputs and outputs are up to date
#if NETCOREAPP
{ PropertyNames.NonExistentFile, "__NonExistentSubDir__\\__NonExistentFile__" },
#else
// Setting `BuildingInsideVisualStudio` indirectly sets NonExistentFile:
// https://github.com/microsoft/msbuild/blob/ab9b2f36a5ff7a85f842b205d5529e77fdc9d7ab/src/Tasks/Microsoft.Common.CurrentVersion.targets#L3462-L3470
{ PropertyNames.BuildingInsideVisualStudio, bool.TrueString },
#endif
{ PropertyNames.BuildProjectReferences, bool.FalseString },
{ PropertyNames.BuildingProject, bool.FalseString },
// retrieve the command-line arguments to the compiler
{ PropertyNames.ProvideCommandLineArgs, bool.TrueString },
// don't actually run the compiler
{ PropertyNames.SkipCompilerExecution, bool.TrueString },
{ PropertyNames.ContinueOnError, PropertyValues.ErrorAndContinue },
// this ensures that the parent project's configuration and platform will be used for
// referenced projects. So, setting Configuration=Release will also cause any project
// references to also be built with Configuration=Release. This is necessary for getting
// a more-likely-to-be-correct output path from project references.
{ PropertyNames.ShouldUnsetParentConfigurationAndPlatform, bool.FalseString }
}.ToImmutableDictionary();
private readonly ImmutableDictionary<string, string> _additionalGlobalProperties;
private readonly ILogger? _msbuildLogger;
private MSB.Evaluation.ProjectCollection? _batchBuildProjectCollection;
private MSBuildDiagnosticLogger? _batchBuildLogger;
~ProjectBuildManager()
{
if (BatchBuildStarted)
{
throw new InvalidOperationException("ProjectBuilderManager.Stop() not called.");
}
}
public ProjectBuildManager(ImmutableDictionary<string, string> additionalGlobalProperties, ILogger? msbuildLogger = null)
{
_additionalGlobalProperties = additionalGlobalProperties ?? ImmutableDictionary<string, string>.Empty;
_msbuildLogger = msbuildLogger;
}
private ImmutableDictionary<string, string> AllGlobalProperties
=> s_defaultGlobalProperties.AddRange(_additionalGlobalProperties);
private static async Task<(MSB.Evaluation.Project? project, DiagnosticLog log)> LoadProjectAsync(
string path, MSB.Evaluation.ProjectCollection? projectCollection, CancellationToken cancellationToken)
{
var log = new DiagnosticLog();
try
{
var loadedProjects = projectCollection?.GetLoadedProjects(path);
if (loadedProjects != null && loadedProjects.Count > 0)
{
Debug.Assert(loadedProjects.Count == 1);
return (loadedProjects.First(), log);
}
using var stream = FileUtilities.OpenAsyncRead(path);
using var readStream = await SerializableBytes.CreateReadableStreamAsync(stream, cancellationToken).ConfigureAwait(false);
using var xmlReader = XmlReader.Create(readStream, s_xmlReaderSettings);
var xml = MSB.Construction.ProjectRootElement.Create(xmlReader, projectCollection);
// When constructing a project from an XmlReader, MSBuild cannot determine the project file path. Setting the
// path explicitly is necessary so that the reserved properties like $(MSBuildProjectDirectory) will work.
xml.FullPath = path;
var project = new MSB.Evaluation.Project(xml, globalProperties: null, toolsVersion: null, projectCollection);
return (project, log);
}
catch (Exception e)
{
log.Add(e, path);
return (project: null, log);
}
}
public Task<(MSB.Evaluation.Project? project, DiagnosticLog log)> LoadProjectAsync(
string path, CancellationToken cancellationToken)
{
if (BatchBuildStarted)
{
return LoadProjectAsync(path, _batchBuildProjectCollection, cancellationToken);
}
else
{
var projectCollection = new MSB.Evaluation.ProjectCollection(AllGlobalProperties);
try
{
return LoadProjectAsync(path, projectCollection, cancellationToken);
}
finally
{
// unload project so collection will release global strings
projectCollection.UnloadAllProjects();
}
}
}
public async Task<string?> TryGetOutputFilePathAsync(
string path, CancellationToken cancellationToken)
{
Debug.Assert(BatchBuildStarted);
// This tries to get the project output path and retrieving the evaluated $(TargetPath) property.
var (project, _) = await LoadProjectAsync(path, cancellationToken).ConfigureAwait(false);
return project?.GetPropertyValue(PropertyNames.TargetPath);
}
public bool BatchBuildStarted { get; private set; }
public void StartBatchBuild(IDictionary<string, string>? globalProperties = null)
{
if (BatchBuildStarted)
{
throw new InvalidOperationException();
}
globalProperties ??= ImmutableDictionary<string, string>.Empty;
var allProperties = s_defaultGlobalProperties.RemoveRange(globalProperties.Keys).AddRange(globalProperties);
_batchBuildProjectCollection = new MSB.Evaluation.ProjectCollection(allProperties);
_batchBuildLogger = new MSBuildDiagnosticLogger()
{
Verbosity = MSB.Framework.LoggerVerbosity.Normal
};
var buildParameters = new MSB.Execution.BuildParameters(_batchBuildProjectCollection)
{
Loggers = _msbuildLogger is null
? (new MSB.Framework.ILogger[] { _batchBuildLogger })
: (new MSB.Framework.ILogger[] { _batchBuildLogger, _msbuildLogger })
};
MSB.Execution.BuildManager.DefaultBuildManager.BeginBuild(buildParameters);
BatchBuildStarted = true;
}
public void EndBatchBuild()
{
if (!BatchBuildStarted)
{
throw new InvalidOperationException();
}
MSB.Execution.BuildManager.DefaultBuildManager.EndBuild();
// unload project so collection will release global strings
_batchBuildProjectCollection?.UnloadAllProjects();
_batchBuildProjectCollection = null;
_batchBuildLogger = null;
BatchBuildStarted = false;
}
public Task<MSB.Execution.ProjectInstance> BuildProjectAsync(
MSB.Evaluation.Project project, DiagnosticLog log, CancellationToken cancellationToken)
{
Debug.Assert(BatchBuildStarted);
var targets = new[] { TargetNames.Compile, TargetNames.CoreCompile };
return BuildProjectAsync(project, targets, log, cancellationToken);
}
private async Task<MSB.Execution.ProjectInstance> BuildProjectAsync(
MSB.Evaluation.Project project, string[] targets, DiagnosticLog log, CancellationToken cancellationToken)
{
// create a project instance to be executed by build engine.
// The executed project will hold the final model of the project after execution via msbuild.
var projectInstance = project.CreateProjectInstance();
// Verify targets
foreach (var target in targets)
{
if (!projectInstance.Targets.ContainsKey(target))
{
log.Add(string.Format(WorkspaceMSBuildResources.Project_does_not_contain_0_target, target), projectInstance.FullPath);
return projectInstance;
}
}
_batchBuildLogger?.SetProjectAndLog(projectInstance.FullPath, log);
var buildRequestData = new MSB.Execution.BuildRequestData(projectInstance, targets);
var result = await BuildAsync(buildRequestData, cancellationToken).ConfigureAwait(false);
if (result.OverallResult == MSB.Execution.BuildResultCode.Failure)
{
if (result.Exception != null)
{
log.Add(result.Exception, projectInstance.FullPath);
}
}
return projectInstance;
}
// this lock is static because we are using the default build manager, and there is only one per process
private static readonly SemaphoreSlim s_buildManagerLock = new(initialCount: 1);
private static async Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
// only allow one build to use the default build manager at a time
using (await s_buildManagerLock.DisposableWaitAsync(cancellationToken).ConfigureAwait(false))
{
return await BuildAsync(MSB.Execution.BuildManager.DefaultBuildManager, requestData, cancellationToken).ConfigureAwait(false);
}
}
private static Task<MSB.Execution.BuildResult> BuildAsync(MSB.Execution.BuildManager buildManager, MSB.Execution.BuildRequestData requestData, CancellationToken cancellationToken)
{
var taskSource = new TaskCompletionSource<MSB.Execution.BuildResult>();
// enable cancellation of build
CancellationTokenRegistration registration = default;
if (cancellationToken.CanBeCanceled)
{
registration = cancellationToken.Register(() =>
{
// Note: We only ever expect that a single submission is being built,
// even though we're calling CancelAllSubmissions(). If MSBuildWorkspace is
// ever updated to support parallel builds, we'll likely need to update this code.
taskSource.TrySetCanceled();
buildManager.CancelAllSubmissions();
registration.Dispose();
});
}
// execute build async
try
{
buildManager.PendBuildRequest(requestData).ExecuteAsync(sub =>
{
// when finished
try
{
var result = sub.BuildResult;
registration.Dispose();
taskSource.TrySetResult(result);
}
catch (Exception e)
{
taskSource.TrySetException(e);
}
}, null);
}
catch (Exception e)
{
taskSource.SetException(e);
}
return taskSource.Task;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/Completion/Providers/AbstractOverrideCompletionProvider.ItemGetter.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal abstract partial class AbstractOverrideCompletionProvider
{
private partial class ItemGetter
{
private readonly CancellationToken _cancellationToken;
private readonly int _position;
private readonly AbstractOverrideCompletionProvider _provider;
private readonly SymbolDisplayFormat _overrideNameFormat = SymbolDisplayFormats.NameFormat.WithParameterOptions(
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeParamsRefOut)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
private readonly Document _document;
private readonly SourceText _text;
private readonly SyntaxTree _syntaxTree;
private readonly int _startLineNumber;
private ItemGetter(
AbstractOverrideCompletionProvider overrideCompletionProvider,
Document document,
int position,
SourceText text,
SyntaxTree syntaxTree,
int startLineNumber,
CancellationToken cancellationToken)
{
_provider = overrideCompletionProvider;
_document = document;
_position = position;
_text = text;
_syntaxTree = syntaxTree;
_startLineNumber = startLineNumber;
_cancellationToken = cancellationToken;
}
public static async Task<ItemGetter> CreateAsync(
AbstractOverrideCompletionProvider overrideCompletionProvider,
Document document,
int position,
CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var startLineNumber = text.Lines.IndexOf(position);
return new ItemGetter(overrideCompletionProvider, document, position, text, syntaxTree, startLineNumber, cancellationToken);
}
public async Task<ImmutableArray<CompletionItem>> GetItemsAsync()
{
// modifiers* override modifiers* type? |
if (!TryCheckForTrailingTokens(_position))
return default;
var startToken = _provider.FindStartingToken(_syntaxTree, _position, _cancellationToken);
if (startToken.Parent == null)
return default;
var semanticModel = await _document.ReuseExistingSpeculativeModelAsync(startToken.Parent, _cancellationToken).ConfigureAwait(false);
if (!_provider.TryDetermineReturnType(startToken, semanticModel, _cancellationToken, out var returnType, out var tokenAfterReturnType) ||
!_provider.TryDetermineModifiers(tokenAfterReturnType, _text, _startLineNumber, out var seenAccessibility, out var modifiers) ||
!TryDetermineOverridableMembers(semanticModel, startToken, seenAccessibility, out var overridableMembers))
{
return default;
}
return _provider.FilterOverrides(overridableMembers, returnType)
.SelectAsArray(m => CreateItem(m, semanticModel, startToken, modifiers));
}
private CompletionItem CreateItem(
ISymbol symbol, SemanticModel semanticModel,
SyntaxToken startToken, DeclarationModifiers modifiers)
{
var position = startToken.SpanStart;
var displayString = symbol.ToMinimalDisplayString(semanticModel, position, _overrideNameFormat);
return MemberInsertionCompletionItem.Create(
displayString,
displayTextSuffix: "",
modifiers,
_startLineNumber,
symbol,
startToken,
position,
rules: GetRules());
}
private bool TryDetermineOverridableMembers(
SemanticModel semanticModel, SyntaxToken startToken,
Accessibility seenAccessibility, out ImmutableArray<ISymbol> overridableMembers)
{
var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, _cancellationToken);
var result = containingType.GetOverridableMembers(_cancellationToken);
// Filter based on accessibility
if (seenAccessibility != Accessibility.NotApplicable)
{
result = result.WhereAsArray(m => m.DeclaredAccessibility == seenAccessibility);
}
overridableMembers = result;
return overridableMembers.Length > 0;
}
private bool TryCheckForTrailingTokens(int position)
{
var root = _syntaxTree.GetRoot(_cancellationToken);
var token = root.FindToken(position);
// Don't want to offer Override completion if there's a token after the current
// position.
if (token.SpanStart > position)
{
return false;
}
// If the next token is also on our line then we don't want to offer completion.
if (IsOnStartLine(token.GetNextToken().SpanStart))
{
return false;
}
return true;
}
private bool IsOnStartLine(int position)
=> _text.Lines.IndexOf(position) == _startLineNumber;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Completion.Providers
{
internal abstract partial class AbstractOverrideCompletionProvider
{
private partial class ItemGetter
{
private readonly CancellationToken _cancellationToken;
private readonly int _position;
private readonly AbstractOverrideCompletionProvider _provider;
private readonly SymbolDisplayFormat _overrideNameFormat = SymbolDisplayFormats.NameFormat.WithParameterOptions(
SymbolDisplayParameterOptions.IncludeDefaultValue |
SymbolDisplayParameterOptions.IncludeExtensionThis |
SymbolDisplayParameterOptions.IncludeType |
SymbolDisplayParameterOptions.IncludeName |
SymbolDisplayParameterOptions.IncludeParamsRefOut)
.AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier);
private readonly Document _document;
private readonly SourceText _text;
private readonly SyntaxTree _syntaxTree;
private readonly int _startLineNumber;
private ItemGetter(
AbstractOverrideCompletionProvider overrideCompletionProvider,
Document document,
int position,
SourceText text,
SyntaxTree syntaxTree,
int startLineNumber,
CancellationToken cancellationToken)
{
_provider = overrideCompletionProvider;
_document = document;
_position = position;
_text = text;
_syntaxTree = syntaxTree;
_startLineNumber = startLineNumber;
_cancellationToken = cancellationToken;
}
public static async Task<ItemGetter> CreateAsync(
AbstractOverrideCompletionProvider overrideCompletionProvider,
Document document,
int position,
CancellationToken cancellationToken)
{
var text = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var syntaxTree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var startLineNumber = text.Lines.IndexOf(position);
return new ItemGetter(overrideCompletionProvider, document, position, text, syntaxTree, startLineNumber, cancellationToken);
}
public async Task<ImmutableArray<CompletionItem>> GetItemsAsync()
{
// modifiers* override modifiers* type? |
if (!TryCheckForTrailingTokens(_position))
return default;
var startToken = _provider.FindStartingToken(_syntaxTree, _position, _cancellationToken);
if (startToken.Parent == null)
return default;
var semanticModel = await _document.ReuseExistingSpeculativeModelAsync(startToken.Parent, _cancellationToken).ConfigureAwait(false);
if (!_provider.TryDetermineReturnType(startToken, semanticModel, _cancellationToken, out var returnType, out var tokenAfterReturnType) ||
!_provider.TryDetermineModifiers(tokenAfterReturnType, _text, _startLineNumber, out var seenAccessibility, out var modifiers) ||
!TryDetermineOverridableMembers(semanticModel, startToken, seenAccessibility, out var overridableMembers))
{
return default;
}
return _provider.FilterOverrides(overridableMembers, returnType)
.SelectAsArray(m => CreateItem(m, semanticModel, startToken, modifiers));
}
private CompletionItem CreateItem(
ISymbol symbol, SemanticModel semanticModel,
SyntaxToken startToken, DeclarationModifiers modifiers)
{
var position = startToken.SpanStart;
var displayString = symbol.ToMinimalDisplayString(semanticModel, position, _overrideNameFormat);
return MemberInsertionCompletionItem.Create(
displayString,
displayTextSuffix: "",
modifiers,
_startLineNumber,
symbol,
startToken,
position,
rules: GetRules());
}
private bool TryDetermineOverridableMembers(
SemanticModel semanticModel, SyntaxToken startToken,
Accessibility seenAccessibility, out ImmutableArray<ISymbol> overridableMembers)
{
var containingType = semanticModel.GetEnclosingSymbol<INamedTypeSymbol>(startToken.SpanStart, _cancellationToken);
var result = containingType.GetOverridableMembers(_cancellationToken);
// Filter based on accessibility
if (seenAccessibility != Accessibility.NotApplicable)
{
result = result.WhereAsArray(m => m.DeclaredAccessibility == seenAccessibility);
}
overridableMembers = result;
return overridableMembers.Length > 0;
}
private bool TryCheckForTrailingTokens(int position)
{
var root = _syntaxTree.GetRoot(_cancellationToken);
var token = root.FindToken(position);
// Don't want to offer Override completion if there's a token after the current
// position.
if (token.SpanStart > position)
{
return false;
}
// If the next token is also on our line then we don't want to offer completion.
if (IsOnStartLine(token.GetNextToken().SpanStart))
{
return false;
}
return true;
}
private bool IsOnStartLine(int position)
=> _text.Lines.IndexOf(position) == _startLineNumber;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Test/CodeModel/VisualBasic/ExternalCodeClassTests.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
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class ExternalCodeClassTests
Inherits AbstractCodeClassTests
#Region "Doc Comment"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDocComment1()
Dim code =
<Code>
''' <summary>This is my comment!</summary>
Class C$$
End Class
</Code>
TestDocComment(code, "<doc>" & vbCrLf & " <summary>This is my comment!</summary>" & vbCrLf & "</doc>")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDocComment2()
Dim code =
<Code>
''' <summary>This is my comment!</summary>
''' <remarks />
Class C$$
End Class
</Code>
TestDocComment(code, "<doc>" & vbCrLf & " <summary>This is my comment!</summary>" & vbCrLf & " <remarks />" & vbCrLf & "</doc>")
End Sub
#End Region
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestExpectedClassMembers()
Dim code =
<Code>
Class C$$
' fields
Private _privateX As Integer
Protected ProtectedX As Integer
Friend InternalX As Integer
Protected Friend ProtectedInternalX As Integer
Public PublicX As Integer
' methods
Private Sub PrivateM()
End Sub
Protected Sub ProtectedM()
End Sub
Friend Sub InternalM()
End Sub
Protected Friend Sub ProtectedInternalM()
End Sub
Public Sub PublicM()
End Sub
End Class
</Code>
TestElement(code,
Sub(codeElement)
Dim members = codeElement.Members
Assert.Equal(9, members.Count)
Dim member1 = members.Item(1)
Assert.Equal("New", member1.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member1.Kind)
Dim member2 = members.Item(2)
Assert.Equal("ProtectedX", member2.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member2.Kind)
Dim member3 = members.Item(3)
Assert.Equal("InternalX", member3.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member3.Kind)
Dim member4 = members.Item(4)
Assert.Equal("ProtectedInternalX", member4.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member4.Kind)
Dim member5 = members.Item(5)
Assert.Equal("PublicX", member5.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member5.Kind)
Dim member6 = members.Item(6)
Assert.Equal("ProtectedM", member6.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member6.Kind)
Dim member7 = members.Item(7)
Assert.Equal("InternalM", member7.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member7.Kind)
Dim member8 = members.Item(8)
Assert.Equal("ProtectedInternalM", member8.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member8.Kind)
Dim member9 = members.Item(9)
Assert.Equal("PublicM", member9.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member9.Kind)
End Sub)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestClassMembersForWithEventsField_Private()
Dim code =
<Code>
Class C
Event E(x As Integer)
End Class
Class D$$
Inherits C
Private WithEvents x As C
Private Sub D_E(x As Integer) Handles Me.E
End Sub
End Class
</Code>
TestElement(code,
Sub(codeElement)
Dim members = codeElement.Members
Assert.Equal(2, members.Count)
Dim member1 = members.Item(1)
Assert.Equal("New", member1.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member1.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPublic, CType(member1, EnvDTE.CodeFunction).Access)
Dim member2 = members.Item(2)
Assert.Equal("_x", member2.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member2.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPrivate, CType(member2, EnvDTE.CodeVariable).Access)
End Sub)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestClassMembersForWithEventsField_Protected()
Dim code =
<Code>
Class C
Event E(x As Integer)
End Class
Class D$$
Inherits C
Protected WithEvents x As C
Private Sub D_E(x As Integer) Handles Me.E
End Sub
End Class
</Code>
TestElement(code,
Sub(codeElement)
Dim members = codeElement.Members
Assert.Equal(3, members.Count)
Dim member1 = members.Item(1)
Assert.Equal("New", member1.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member1.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPublic, CType(member1, EnvDTE.CodeFunction).Access)
Dim member2 = members.Item(2)
Assert.Equal("_x", member2.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member2.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPrivate, CType(member2, EnvDTE.CodeVariable).Access)
Dim member3 = members.Item(3)
Assert.Equal("x", member3.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member3.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessProtected Or EnvDTE.vsCMAccess.vsCMAccessWithEvents, CType(member3, EnvDTE.CodeVariable).Access)
End Sub)
End Sub
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean
Get
Return True
End Get
End Property
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class ExternalCodeClassTests
Inherits AbstractCodeClassTests
#Region "Doc Comment"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDocComment1()
Dim code =
<Code>
''' <summary>This is my comment!</summary>
Class C$$
End Class
</Code>
TestDocComment(code, "<doc>" & vbCrLf & " <summary>This is my comment!</summary>" & vbCrLf & "</doc>")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestDocComment2()
Dim code =
<Code>
''' <summary>This is my comment!</summary>
''' <remarks />
Class C$$
End Class
</Code>
TestDocComment(code, "<doc>" & vbCrLf & " <summary>This is my comment!</summary>" & vbCrLf & " <remarks />" & vbCrLf & "</doc>")
End Sub
#End Region
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestExpectedClassMembers()
Dim code =
<Code>
Class C$$
' fields
Private _privateX As Integer
Protected ProtectedX As Integer
Friend InternalX As Integer
Protected Friend ProtectedInternalX As Integer
Public PublicX As Integer
' methods
Private Sub PrivateM()
End Sub
Protected Sub ProtectedM()
End Sub
Friend Sub InternalM()
End Sub
Protected Friend Sub ProtectedInternalM()
End Sub
Public Sub PublicM()
End Sub
End Class
</Code>
TestElement(code,
Sub(codeElement)
Dim members = codeElement.Members
Assert.Equal(9, members.Count)
Dim member1 = members.Item(1)
Assert.Equal("New", member1.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member1.Kind)
Dim member2 = members.Item(2)
Assert.Equal("ProtectedX", member2.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member2.Kind)
Dim member3 = members.Item(3)
Assert.Equal("InternalX", member3.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member3.Kind)
Dim member4 = members.Item(4)
Assert.Equal("ProtectedInternalX", member4.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member4.Kind)
Dim member5 = members.Item(5)
Assert.Equal("PublicX", member5.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member5.Kind)
Dim member6 = members.Item(6)
Assert.Equal("ProtectedM", member6.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member6.Kind)
Dim member7 = members.Item(7)
Assert.Equal("InternalM", member7.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member7.Kind)
Dim member8 = members.Item(8)
Assert.Equal("ProtectedInternalM", member8.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member8.Kind)
Dim member9 = members.Item(9)
Assert.Equal("PublicM", member9.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member9.Kind)
End Sub)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestClassMembersForWithEventsField_Private()
Dim code =
<Code>
Class C
Event E(x As Integer)
End Class
Class D$$
Inherits C
Private WithEvents x As C
Private Sub D_E(x As Integer) Handles Me.E
End Sub
End Class
</Code>
TestElement(code,
Sub(codeElement)
Dim members = codeElement.Members
Assert.Equal(2, members.Count)
Dim member1 = members.Item(1)
Assert.Equal("New", member1.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member1.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPublic, CType(member1, EnvDTE.CodeFunction).Access)
Dim member2 = members.Item(2)
Assert.Equal("_x", member2.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member2.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPrivate, CType(member2, EnvDTE.CodeVariable).Access)
End Sub)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestClassMembersForWithEventsField_Protected()
Dim code =
<Code>
Class C
Event E(x As Integer)
End Class
Class D$$
Inherits C
Protected WithEvents x As C
Private Sub D_E(x As Integer) Handles Me.E
End Sub
End Class
</Code>
TestElement(code,
Sub(codeElement)
Dim members = codeElement.Members
Assert.Equal(3, members.Count)
Dim member1 = members.Item(1)
Assert.Equal("New", member1.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementFunction, member1.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPublic, CType(member1, EnvDTE.CodeFunction).Access)
Dim member2 = members.Item(2)
Assert.Equal("_x", member2.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member2.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessPrivate, CType(member2, EnvDTE.CodeVariable).Access)
Dim member3 = members.Item(3)
Assert.Equal("x", member3.Name)
Assert.Equal(EnvDTE.vsCMElement.vsCMElementVariable, member3.Kind)
Assert.Equal(EnvDTE.vsCMAccess.vsCMAccessProtected Or EnvDTE.vsCMAccess.vsCMAccessWithEvents, CType(member3, EnvDTE.CodeVariable).Access)
End Sub)
End Sub
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean
Get
Return True
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/Core/Extensibility/NavigationBar/NavigationBarSelectedItems.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor
{
internal class NavigationBarSelectedTypeAndMember
{
public NavigationBarItem TypeItem { get; }
public bool ShowTypeItemGrayed { get; }
public NavigationBarItem MemberItem { get; }
public bool ShowMemberItemGrayed { get; }
public NavigationBarSelectedTypeAndMember(NavigationBarItem typeItem, NavigationBarItem memberItem)
{
TypeItem = typeItem;
MemberItem = memberItem;
}
public NavigationBarSelectedTypeAndMember(
NavigationBarItem typeItem,
bool showTypeItemGrayed,
NavigationBarItem memberItem,
bool showMemberItemGrayed)
: this(typeItem, memberItem)
{
ShowTypeItemGrayed = showTypeItemGrayed;
ShowMemberItemGrayed = showMemberItemGrayed;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.Editor
{
internal class NavigationBarSelectedTypeAndMember
{
public NavigationBarItem TypeItem { get; }
public bool ShowTypeItemGrayed { get; }
public NavigationBarItem MemberItem { get; }
public bool ShowMemberItemGrayed { get; }
public NavigationBarSelectedTypeAndMember(NavigationBarItem typeItem, NavigationBarItem memberItem)
{
TypeItem = typeItem;
MemberItem = memberItem;
}
public NavigationBarSelectedTypeAndMember(
NavigationBarItem typeItem,
bool showTypeItemGrayed,
NavigationBarItem memberItem,
bool showMemberItemGrayed)
: this(typeItem, memberItem)
{
ShowTypeItemGrayed = showTypeItemGrayed;
ShowMemberItemGrayed = showMemberItemGrayed;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Remote/ServiceHub/Services/InheritanceMargin/RemoteInheritanceMarginService.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 System.Threading.Tasks;
using Microsoft.CodeAnalysis.InheritanceMargin;
namespace Microsoft.CodeAnalysis.Remote
{
internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService
{
internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService>
{
protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments)
{
return new RemoteInheritanceMarginService(arguments);
}
}
public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments)
{
}
public ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync(
PinnedSolutionInfo pinnedSolutionInfo,
ProjectId projectId,
ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers,
CancellationToken cancellationToken)
=> RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(pinnedSolutionInfo, cancellationToken).ConfigureAwait(false);
return await InheritanceMarginServiceHelper
.GetInheritanceMemberItemAsync(solution, projectId, symbolKeyAndLineNumbers, cancellationToken)
.ConfigureAwait(false);
}, cancellationToken);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.InheritanceMargin;
namespace Microsoft.CodeAnalysis.Remote
{
internal sealed class RemoteInheritanceMarginService : BrokeredServiceBase, IRemoteInheritanceMarginService
{
internal sealed class Factory : FactoryBase<IRemoteInheritanceMarginService>
{
protected override IRemoteInheritanceMarginService CreateService(in ServiceConstructionArguments arguments)
{
return new RemoteInheritanceMarginService(arguments);
}
}
public RemoteInheritanceMarginService(in ServiceConstructionArguments arguments) : base(in arguments)
{
}
public ValueTask<ImmutableArray<SerializableInheritanceMarginItem>> GetInheritanceMarginItemsAsync(
PinnedSolutionInfo pinnedSolutionInfo,
ProjectId projectId,
ImmutableArray<(SymbolKey symbolKey, int lineNumber)> symbolKeyAndLineNumbers,
CancellationToken cancellationToken)
=> RunServiceAsync(async cancellationToken =>
{
var solution = await GetSolutionAsync(pinnedSolutionInfo, cancellationToken).ConfigureAwait(false);
return await InheritanceMarginServiceHelper
.GetInheritanceMemberItemAsync(solution, projectId, symbolKeyAndLineNumbers, cancellationToken)
.ConfigureAwait(false);
}, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/IntroduceVariable/AbstractIntroduceVariableService.State_Attribute.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private partial class State
{
private bool IsInAttributeContext()
{
if (!_service.IsInAttributeArgumentInitializer(Expression))
{
return false;
}
// Have to make sure we're on or inside a type decl so that we have some place to
// put the result.
return IsInTypeDeclarationOrValidCompilationUnit();
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
namespace Microsoft.CodeAnalysis.IntroduceVariable
{
internal partial class AbstractIntroduceVariableService<TService, TExpressionSyntax, TTypeSyntax, TTypeDeclarationSyntax, TQueryExpressionSyntax, TNameSyntax>
{
private partial class State
{
private bool IsInAttributeContext()
{
if (!_service.IsInAttributeArgumentInitializer(Expression))
{
return false;
}
// Have to make sure we're on or inside a type decl so that we have some place to
// put the result.
return IsInTypeDeclarationOrValidCompilationUnit();
}
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Test/Semantic/Semantics/ScriptSemanticsTests.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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ScriptSemanticsTests
Inherits BasicTestBase
<WorkItem(530404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530404")>
<Fact>
Public Sub DiagnosticsPass()
Dim source0 = "
Function F(e As System.Linq.Expressions.Expression(Of System.Func(Of Object))) As Object
Return e.Compile()()
End Function"
Dim c0 = CreateSubmission(source0, {SystemCoreRef})
Dim source1 = "
F(Function()
Return Nothing
End Function)
"
Dim c1 = CreateSubmission(source1, {SystemCoreRef}, previous:=c0)
AssertTheseDiagnostics(c1,
<errors>
BC36675: Statement lambdas cannot be converted to expression trees.
F(Function()
~~~~~~~~~~~
</errors>)
End Sub
<Fact>
<WorkItem(10023, "https://github.com/dotnet/roslyn/issues/10023")>
Public Sub Errors_01()
Dim code = "System.Console.WriteLine(1)"
Dim compilationUnit = VisualBasic.SyntaxFactory.ParseCompilationUnit(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
Dim syntaxTree = compilationUnit.SyntaxTree
Dim compilation = CreateCompilationWithMscorlib45({syntaxTree}, assemblyName:="Errors_01", options:=TestOptions.ReleaseExe)
Dim semanticModel = compilation.GetSemanticModel(syntaxTree, True)
Dim node5 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Null(semanticModel.GetSymbolInfo(node5.Name).Symbol)
compilation.AssertTheseDiagnostics(
<expected>
BC30420: 'Sub Main' was not found in 'Errors_01'.
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
compilation = CreateCompilationWithMscorlib45({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("Script"), assemblyName:="Errors_01")
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Null(semanticModel.GetSymbolInfo(node5.Name).Symbol)
compilation.AssertTheseDiagnostics(
<expected>
BC30420: 'Sub Main' was not found in 'Errors_01'.
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe)
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
CompileAndVerify(compilation, expectedOutput:="1").VerifyDiagnostics()
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("Script"))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
CompileAndVerify(compilation, expectedOutput:="1").VerifyDiagnostics()
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName(""))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC2014: the value '' is invalid for option 'ScriptClassName'
</expected>
)
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName(Nothing))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC2014: the value 'Nothing' is invalid for option 'ScriptClassName'
</expected>
)
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("a" + ChrW(0) + "b"))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("ScriptClassName", "a" + ChrW(0) + "b").WithLocation(1, 1)
)
End Sub
<Fact>
<WorkItem(10023, "https://github.com/dotnet/roslyn/issues/10023")>
Public Sub Errors_02()
Dim compilationUnit = VisualBasic.SyntaxFactory.ParseCompilationUnit("System.Console.WriteLine(1)", options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
Dim syntaxTree1 = compilationUnit.SyntaxTree
Dim syntaxTree2 = SyntaxFactory.ParseSyntaxTree("System.Console.WriteLine(2)", options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
Dim node1 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree1)
Assert.Equal("WriteLine", node1.Name.ToString())
Dim node2 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree2)
Assert.Equal("WriteLine", node2.Name.ToString())
Dim compilation = CreateCompilationWithMscorlib45({syntaxTree1, syntaxTree2})
Dim semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True)
Dim semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True)
Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol)
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
compilation = CreateCompilationWithMscorlib45({syntaxTree2, syntaxTree1})
semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True)
semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True)
Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol)
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
End Sub
Private Shared Function ErrorTestsGetNode(syntaxTree As SyntaxTree) As MemberAccessExpressionSyntax
Dim node1 = DirectCast(syntaxTree.GetRoot(), CompilationUnitSyntax)
Dim node3 = DirectCast(node1.Members.First(), ExpressionStatementSyntax)
Dim node4 = DirectCast(node3.Expression, InvocationExpressionSyntax)
Dim node5 = DirectCast(node4.Expression, MemberAccessExpressionSyntax)
Return node5
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.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests
Public Class ScriptSemanticsTests
Inherits BasicTestBase
<WorkItem(530404, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530404")>
<Fact>
Public Sub DiagnosticsPass()
Dim source0 = "
Function F(e As System.Linq.Expressions.Expression(Of System.Func(Of Object))) As Object
Return e.Compile()()
End Function"
Dim c0 = CreateSubmission(source0, {SystemCoreRef})
Dim source1 = "
F(Function()
Return Nothing
End Function)
"
Dim c1 = CreateSubmission(source1, {SystemCoreRef}, previous:=c0)
AssertTheseDiagnostics(c1,
<errors>
BC36675: Statement lambdas cannot be converted to expression trees.
F(Function()
~~~~~~~~~~~
</errors>)
End Sub
<Fact>
<WorkItem(10023, "https://github.com/dotnet/roslyn/issues/10023")>
Public Sub Errors_01()
Dim code = "System.Console.WriteLine(1)"
Dim compilationUnit = VisualBasic.SyntaxFactory.ParseCompilationUnit(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
Dim syntaxTree = compilationUnit.SyntaxTree
Dim compilation = CreateCompilationWithMscorlib45({syntaxTree}, assemblyName:="Errors_01", options:=TestOptions.ReleaseExe)
Dim semanticModel = compilation.GetSemanticModel(syntaxTree, True)
Dim node5 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Null(semanticModel.GetSymbolInfo(node5.Name).Symbol)
compilation.AssertTheseDiagnostics(
<expected>
BC30420: 'Sub Main' was not found in 'Errors_01'.
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
compilation = CreateCompilationWithMscorlib45({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("Script"), assemblyName:="Errors_01")
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Null(semanticModel.GetSymbolInfo(node5.Name).Symbol)
compilation.AssertTheseDiagnostics(
<expected>
BC30420: 'Sub Main' was not found in 'Errors_01'.
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe)
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
CompileAndVerify(compilation, expectedOutput:="1").VerifyDiagnostics()
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("Script"))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
CompileAndVerify(compilation, expectedOutput:="1").VerifyDiagnostics()
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName(""))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC2014: the value '' is invalid for option 'ScriptClassName'
</expected>
)
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName(Nothing))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC2014: the value 'Nothing' is invalid for option 'ScriptClassName'
</expected>
)
syntaxTree = SyntaxFactory.ParseSyntaxTree(code, options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
compilation = CreateCompilationWithMscorlib45AndVBRuntime({syntaxTree}, options:=TestOptions.ReleaseExe.WithScriptClassName("a" + ChrW(0) + "b"))
semanticModel = compilation.GetSemanticModel(syntaxTree, True)
node5 = ErrorTestsGetNode(syntaxTree)
Assert.Equal("WriteLine", node5.Name.ToString())
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel.GetSymbolInfo(node5.Name).Symbol.ToTestDisplayString())
compilation.VerifyDiagnostics(
Diagnostic(ERRID.ERR_InvalidSwitchValue).WithArguments("ScriptClassName", "a" + ChrW(0) + "b").WithLocation(1, 1)
)
End Sub
<Fact>
<WorkItem(10023, "https://github.com/dotnet/roslyn/issues/10023")>
Public Sub Errors_02()
Dim compilationUnit = VisualBasic.SyntaxFactory.ParseCompilationUnit("System.Console.WriteLine(1)", options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
Dim syntaxTree1 = compilationUnit.SyntaxTree
Dim syntaxTree2 = SyntaxFactory.ParseSyntaxTree("System.Console.WriteLine(2)", options:=New VisualBasicParseOptions(kind:=SourceCodeKind.Script))
Dim node1 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree1)
Assert.Equal("WriteLine", node1.Name.ToString())
Dim node2 As MemberAccessExpressionSyntax = ErrorTestsGetNode(syntaxTree2)
Assert.Equal("WriteLine", node2.Name.ToString())
Dim compilation = CreateCompilationWithMscorlib45({syntaxTree1, syntaxTree2})
Dim semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True)
Dim semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True)
Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol)
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
compilation = CreateCompilationWithMscorlib45({syntaxTree2, syntaxTree1})
semanticModel1 = compilation.GetSemanticModel(syntaxTree1, True)
semanticModel2 = compilation.GetSemanticModel(syntaxTree2, True)
Assert.Null(semanticModel1.GetSymbolInfo(node1.Name).Symbol)
Assert.Equal("Sub System.Console.WriteLine(value As System.Int32)", semanticModel2.GetSymbolInfo(node2.Name).Symbol.ToTestDisplayString())
compilation.AssertTheseDiagnostics(
<expected>
BC30001: Statement is not valid in a namespace.
System.Console.WriteLine(1)
~~~~~~~~~~~~~~~~~~~~~~~~~~~
</expected>
)
End Sub
Private Shared Function ErrorTestsGetNode(syntaxTree As SyntaxTree) As MemberAccessExpressionSyntax
Dim node1 = DirectCast(syntaxTree.GetRoot(), CompilationUnitSyntax)
Dim node3 = DirectCast(node1.Members.First(), ExpressionStatementSyntax)
Dim node4 = DirectCast(node3.Expression, InvocationExpressionSyntax)
Dim node5 = DirectCast(node4.Expression, MemberAccessExpressionSyntax)
Return node5
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Test/Core/Syntax/XmlHelpers.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class XmlOptions
{
public bool Trivia
{
get;
set;
}
public bool Spans
{
get;
set;
}
public bool ReflectionInfo
{
get;
set;
}
public bool Text
{
get;
set;
}
public bool Errors
{
get;
set;
}
}
public static class XmlHelpers
{
private static void AddNodeInfo(NodeInfo info, XElement xml)
{
xml.Add(new XAttribute("Type", info.ClassName));
foreach (var f in info.FieldInfos)
{
if (!(f.PropertyName.Contains("Span") || f.PropertyName.Contains("Kind") || f.PropertyName.Contains("Text") || f.PropertyName.Contains("IsMissing")))
{
xml.Add(@"<<%= f.PropertyName %> FieldType=<%= f.FieldType.Name %>><%= New XCData(f.Value.ToString) %></>");
}
}
}
public static void AddInfo(SyntaxNode node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddInfo(SyntaxNodeOrToken node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddInfo(SyntaxToken node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddInfo(SyntaxTrivia node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddErrors(XElement xml, IEnumerable<Diagnostic> errors, XmlOptions options)
{
xml.Add(@"<Errors>
<%= From e In errors
Let l = e.Location
Select If(l.InSource,
<Error Code=<%= e.Info.MessageIdentifier.ToString %> Severity=<%= e.Severity.ToString %>>
<%= If(options.Text, <Message><%= e.GetMessage(Globalization.CultureInfo.CurrentCulture) %></Message>, Nothing) %>
<%= If(options.Spans, <Span Start=<%= l.SourceSpan.Start %> End=<%= l.SourceSpan.End %> Length=<%= l.SourceSpan.Length %>/>, Nothing) %>
</Error>,
<Error Code=<%= e.Info.MessageIdentifier.ToString %> Severity=<%= e.Severity.ToString %>>
<%= If(options.Text, <Message><%= e.GetMessage(Globalization.CultureInfo.CurrentCulture) %></Message>, Nothing) %>
</Error>
) %>
</Errors>");
}
public static XElement ToXml(this SyntaxNodeOrToken node, SyntaxTree syntaxTree, XmlOptions options = null)
{
XElement xml = null;
if (node.IsNode)
{
xml = ToXml(node.AsNode(), syntaxTree, options);
}
else
{
xml = ToXml(node.AsToken(), syntaxTree, options);
}
return xml;
}
public static XElement ToXml(this SyntaxNode node, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement xml = null;
if (node != null)
{
xml = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", node.GetKind()),
new XAttribute("IsMissing", node.IsMissing));
if (options.Spans)
{
xml.Add(@"<Span Start=<%= node.SpanStart %> End=<%= node.Span.End %> Length=<%= node.Span.Length %>/>");
xml.Add(@"<FullSpan Start=<%= node.FullSpan.Start %> End=<%= node.FullSpan.End %> Length=<%= node.FullSpan.Length %>/>");
}
if (options.ReflectionInfo)
{
AddInfo(node, xml, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(node).Any())
{
AddErrors(xml, syntaxTree.GetDiagnostics(node), options);
}
}
foreach (var c in node.ChildNodesAndTokens())
{
xml.Add(c.ToXml(syntaxTree, options));
}
}
return xml;
}
public static XElement ToXml(this SyntaxToken token, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement retVal = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", token.GetKind()),
new XAttribute("IsMissing", token.IsMissing));
if (options.Spans)
{
retVal.Add(@"<Span Start=<%= token.SpanStart %> End=<%= token.Span.End %> Length=<%= token.Span.Length %>/>");
retVal.Add(@"<FullSpan Start=<%= token.FullSpan.Start %> End=<%= token.FullSpan.End %> Length=<%= token.FullSpan.Length %>/>");
}
if (options.Text)
{
retVal.Add(@"<Text><%= New XCData(token.GetText()) %></Text>");
}
if (options.ReflectionInfo)
{
AddInfo(token, retVal, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(token).Any())
{
AddErrors(retVal, syntaxTree.GetDiagnostics(token), options);
}
}
if (options.Trivia)
{
if (token.LeadingTrivia.Any())
{
retVal.Add(@"<LeadingTrivia><%= From t In token.LeadingTrivia Select t.ToXml(syntaxTree, options) %></LeadingTrivia>");
}
if (token.TrailingTrivia.Any())
{
retVal.Add(@"<TrailingTrivia><%= From t In token.TrailingTrivia Select t.ToXml(syntaxTree, options) %></TrailingTrivia>");
}
}
return retVal;
}
public static XElement ToXml(this SyntaxTrivia trivia, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement retVal = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", trivia.GetKind()),
new XAttribute("IsMissing", false));
if (options.Spans)
{
retVal.Add(@"<Span Start=<%= trivia.SpanStart %> End=<%= trivia.Span.End %> Length=<%= trivia.Span.Length %>/>");
retVal.Add(@"<FullSpan Start=<%= trivia.FullSpan.Start %> End=<%= trivia.FullSpan.End %> Length=<%= trivia.FullSpan.Length %>/>");
}
if (options.Text)
{
retVal.Add(@"<Text><%= New XCData(trivia.GetText()) %></Text>");
}
if (options.ReflectionInfo)
{
AddInfo(trivia, retVal, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(trivia).Any())
{
AddErrors(retVal, syntaxTree.GetDiagnostics(trivia), options);
}
}
if (trivia.HasStructure)
{
retVal.Add(trivia.GetStructure().ToXml(syntaxTree, options));
}
return retVal;
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class XmlOptions
{
public bool Trivia
{
get;
set;
}
public bool Spans
{
get;
set;
}
public bool ReflectionInfo
{
get;
set;
}
public bool Text
{
get;
set;
}
public bool Errors
{
get;
set;
}
}
public static class XmlHelpers
{
private static void AddNodeInfo(NodeInfo info, XElement xml)
{
xml.Add(new XAttribute("Type", info.ClassName));
foreach (var f in info.FieldInfos)
{
if (!(f.PropertyName.Contains("Span") || f.PropertyName.Contains("Kind") || f.PropertyName.Contains("Text") || f.PropertyName.Contains("IsMissing")))
{
xml.Add(@"<<%= f.PropertyName %> FieldType=<%= f.FieldType.Name %>><%= New XCData(f.Value.ToString) %></>");
}
}
}
public static void AddInfo(SyntaxNode node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddInfo(SyntaxNodeOrToken node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddInfo(SyntaxToken node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddInfo(SyntaxTrivia node, XElement xml, XmlOptions options)
{
AddNodeInfo(node.GetNodeInfo(), xml);
}
public static void AddErrors(XElement xml, IEnumerable<Diagnostic> errors, XmlOptions options)
{
xml.Add(@"<Errors>
<%= From e In errors
Let l = e.Location
Select If(l.InSource,
<Error Code=<%= e.Info.MessageIdentifier.ToString %> Severity=<%= e.Severity.ToString %>>
<%= If(options.Text, <Message><%= e.GetMessage(Globalization.CultureInfo.CurrentCulture) %></Message>, Nothing) %>
<%= If(options.Spans, <Span Start=<%= l.SourceSpan.Start %> End=<%= l.SourceSpan.End %> Length=<%= l.SourceSpan.Length %>/>, Nothing) %>
</Error>,
<Error Code=<%= e.Info.MessageIdentifier.ToString %> Severity=<%= e.Severity.ToString %>>
<%= If(options.Text, <Message><%= e.GetMessage(Globalization.CultureInfo.CurrentCulture) %></Message>, Nothing) %>
</Error>
) %>
</Errors>");
}
public static XElement ToXml(this SyntaxNodeOrToken node, SyntaxTree syntaxTree, XmlOptions options = null)
{
XElement xml = null;
if (node.IsNode)
{
xml = ToXml(node.AsNode(), syntaxTree, options);
}
else
{
xml = ToXml(node.AsToken(), syntaxTree, options);
}
return xml;
}
public static XElement ToXml(this SyntaxNode node, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement xml = null;
if (node != null)
{
xml = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", node.GetKind()),
new XAttribute("IsMissing", node.IsMissing));
if (options.Spans)
{
xml.Add(@"<Span Start=<%= node.SpanStart %> End=<%= node.Span.End %> Length=<%= node.Span.Length %>/>");
xml.Add(@"<FullSpan Start=<%= node.FullSpan.Start %> End=<%= node.FullSpan.End %> Length=<%= node.FullSpan.Length %>/>");
}
if (options.ReflectionInfo)
{
AddInfo(node, xml, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(node).Any())
{
AddErrors(xml, syntaxTree.GetDiagnostics(node), options);
}
}
foreach (var c in node.ChildNodesAndTokens())
{
xml.Add(c.ToXml(syntaxTree, options));
}
}
return xml;
}
public static XElement ToXml(this SyntaxToken token, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement retVal = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", token.GetKind()),
new XAttribute("IsMissing", token.IsMissing));
if (options.Spans)
{
retVal.Add(@"<Span Start=<%= token.SpanStart %> End=<%= token.Span.End %> Length=<%= token.Span.Length %>/>");
retVal.Add(@"<FullSpan Start=<%= token.FullSpan.Start %> End=<%= token.FullSpan.End %> Length=<%= token.FullSpan.Length %>/>");
}
if (options.Text)
{
retVal.Add(@"<Text><%= New XCData(token.GetText()) %></Text>");
}
if (options.ReflectionInfo)
{
AddInfo(token, retVal, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(token).Any())
{
AddErrors(retVal, syntaxTree.GetDiagnostics(token), options);
}
}
if (options.Trivia)
{
if (token.LeadingTrivia.Any())
{
retVal.Add(@"<LeadingTrivia><%= From t In token.LeadingTrivia Select t.ToXml(syntaxTree, options) %></LeadingTrivia>");
}
if (token.TrailingTrivia.Any())
{
retVal.Add(@"<TrailingTrivia><%= From t In token.TrailingTrivia Select t.ToXml(syntaxTree, options) %></TrailingTrivia>");
}
}
return retVal;
}
public static XElement ToXml(this SyntaxTrivia trivia, SyntaxTree syntaxTree, XmlOptions options = null)
{
if (options == null)
{
options = new XmlOptions();
}
XElement retVal = new XElement("Node",
new XAttribute("IsToken", false),
new XAttribute("IsTrivia", true),
new XAttribute("Kind", trivia.GetKind()),
new XAttribute("IsMissing", false));
if (options.Spans)
{
retVal.Add(@"<Span Start=<%= trivia.SpanStart %> End=<%= trivia.Span.End %> Length=<%= trivia.Span.Length %>/>");
retVal.Add(@"<FullSpan Start=<%= trivia.FullSpan.Start %> End=<%= trivia.FullSpan.End %> Length=<%= trivia.FullSpan.Length %>/>");
}
if (options.Text)
{
retVal.Add(@"<Text><%= New XCData(trivia.GetText()) %></Text>");
}
if (options.ReflectionInfo)
{
AddInfo(trivia, retVal, options);
}
if (options.Errors)
{
if (syntaxTree.GetDiagnostics(trivia).Any())
{
AddErrors(retVal, syntaxTree.GetDiagnostics(trivia), options);
}
}
if (trivia.HasStructure)
{
retVal.Add(trivia.GetStructure().ToXml(syntaxTree, options));
}
return retVal;
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/ExpressionEvaluator/CSharp/Test/ExpressionCompiler/TupleTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class TupleTests : ExpressionCompilerTestBase
{
[Fact]
public void Literal()
{
var source =
@"class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A", "B" }, tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
methodData.VerifyIL(
@"{
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void DuplicateValueTupleBetweenMscorlibAndLibrary()
{
var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]";
var corlib_cs = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class ValueType { }
public struct Void { }
public class Attribute { }
}
namespace System.Reflection
{
public class AssemblyVersionAttribute : Attribute
{
public AssemblyVersionAttribute(String version) { }
}
}";
string valuetuple_cs = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib");
corlibWithoutVT.VerifyDiagnostics();
var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference();
var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib");
corlibWithVT.VerifyDiagnostics();
var source =
@"class C
{
static (int, int) M()
{
(int, int) t = (1, 2);
return t;
}
}
";
var app = CreateEmptyCompilation(source + valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll);
app.VerifyDiagnostics();
// Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple)
var runtime = CreateRuntimeInstance(new[] { app.ToModuleInstance(), corlibWithVT.ToModuleInstance() });
var evalContext = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var compileResult = evalContext.CompileExpression("(1, 2)", out error, testData);
Assert.Null(error);
using (ModuleMetadata block = ModuleMetadata.CreateFromStream(new MemoryStream(compileResult.Assembly)))
{
var reader = block.MetadataReader;
var appRef = app.Assembly.Identity.Name;
AssertEx.SetEqual(new[] { "corlib 2.0", appRef + " 0.0" }, reader.DumpAssemblyReferences());
AssertEx.SetEqual(new[] {
"Object, System, AssemblyReference:corlib",
"ValueTuple`2, System, AssemblyReference:" + appRef // ValueTuple comes from app, not corlib
},
reader.DumpTypeReferences());
}
}
[Fact]
public void TupleElementNamesAttribute_NotAvailable()
{
var source =
@"namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 _1, T2 _2)
{
Item1 = _1;
Item2 = _2;
}
}
}
class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
Assert.Null(customTypeInfo);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@" {
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void Local()
{
var source =
@"class C
{
static void M()
{
(int A\u1234, int \u1234B) o = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
Assert.True(method.ReturnType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}}", '\u1234'));
locals.Free();
});
}
[Fact]
public void Constant()
{
var source =
@"class A<T>
{
internal class B<U>
{
}
}
class C
{
static (object, object) F;
static void M()
{
const A<(int, int A)>.B<(object B, object)>[] c = null;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(returnType.ContainsTuple());
VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
[Fact]
public void LongTupleLocalElement_NoNames()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, 3, 4, 5, 6, 7, 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item4 + x.Item8", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 19 (0x13)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item4""
IL_0006: ldloc.0
IL_0007: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_000c: ldfld ""int System.ValueTuple<int>.Item1""
IL_0011: add
IL_0012: ret
}");
});
}
[Fact]
public void LongTupleLocalElement_Names()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, Three: 3, Four: 4, 5, 6, 7, Eight: 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item8 + x.Eight", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0006: ldfld ""int System.ValueTuple<int>.Item1""
IL_000b: ldloc.0
IL_000c: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0011: ldfld ""int System.ValueTuple<int>.Item1""
IL_0016: add
IL_0017: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void DeclareLocal()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
"(int A, int B) y = x;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Null(tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@"{
// Code size 64 (0x40)
.maxstack 6
.locals init (System.ValueTuple<int, int> V_0) //x
IL_0000: ldtoken ""System.ValueTuple<int, int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.5
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.845151BC3876B3B783409FD71AF3665D783D8036161B4A2D2ACD27E1A0FCEDF7""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""y""
IL_0034: call ""System.ValueTuple<int, int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueTuple<int, int>>(string)""
IL_0039: ldloc.0
IL_003a: stobj ""System.ValueTuple<int, int>""
IL_003f: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
public void AliasElement()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
// (int A, (int, int D) B)[] t;
var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
var alias = new Alias(
DkmClrAliasKind.Variable,
"t",
"t",
"System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
CustomTypeInfo.PayloadTypeId,
CustomTypeInfo.Encode(null, aliasElementNames));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: ImmutableArray.Create(alias),
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Verify();
diagnostics.Free();
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(aliasElementNames, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = (TypeSymbol)method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""t""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.ValueTuple<int, System.ValueTuple<int, int>>[]""
IL_000f: ret
}");
locals.Free();
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
public void AliasElement_NoNames()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var alias = new Alias(
DkmClrAliasKind.Variable,
"x",
"x",
"System.ValueTuple`8[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.ValueTuple`2[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
Guid.Empty,
null);
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
context.CompileExpression(
"x.Item4 + x.Item8",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(alias),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
null,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldstr ""x""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_000f: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Item4""
IL_0014: ldstr ""x""
IL_0019: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_001e: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Rest""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002d: add
IL_002e: ret
}");
});
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.VisualStudio.Debugger.Clr;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class TupleTests : ExpressionCompilerTestBase
{
[Fact]
public void Literal()
{
var source =
@"class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A", "B" }, tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
methodData.VerifyIL(
@"{
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void DuplicateValueTupleBetweenMscorlibAndLibrary()
{
var versionTemplate = @"[assembly: System.Reflection.AssemblyVersion(""{0}.0.0.0"")]";
var corlib_cs = @"
namespace System
{
public class Object { }
public struct Int32 { }
public struct Boolean { }
public class String { }
public class ValueType { }
public struct Void { }
public class Attribute { }
}
namespace System.Reflection
{
public class AssemblyVersionAttribute : Attribute
{
public AssemblyVersionAttribute(String version) { }
}
}";
string valuetuple_cs = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2) => (Item1, Item2) = (item1, item2);
}
}";
var corlibWithoutVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "1") + corlib_cs) }, assemblyName: "corlib");
corlibWithoutVT.VerifyDiagnostics();
var corlibWithoutVTRef = corlibWithoutVT.EmitToImageReference();
var corlibWithVT = CreateEmptyCompilation(new[] { Parse(String.Format(versionTemplate, "2") + corlib_cs + valuetuple_cs) }, assemblyName: "corlib");
corlibWithVT.VerifyDiagnostics();
var source =
@"class C
{
static (int, int) M()
{
(int, int) t = (1, 2);
return t;
}
}
";
var app = CreateEmptyCompilation(source + valuetuple_cs, references: new[] { corlibWithoutVTRef }, options: TestOptions.DebugDll);
app.VerifyDiagnostics();
// Create EE context with app assembly (including ValueTuple) and a more recent corlib (also including ValueTuple)
var runtime = CreateRuntimeInstance(new[] { app.ToModuleInstance(), corlibWithVT.ToModuleInstance() });
var evalContext = CreateMethodContext(runtime, "C.M");
string error;
var testData = new CompilationTestData();
var compileResult = evalContext.CompileExpression("(1, 2)", out error, testData);
Assert.Null(error);
using (ModuleMetadata block = ModuleMetadata.CreateFromStream(new MemoryStream(compileResult.Assembly)))
{
var reader = block.MetadataReader;
var appRef = app.Assembly.Identity.Name;
AssertEx.SetEqual(new[] { "corlib 2.0", appRef + " 0.0" }, reader.DumpAssemblyReferences());
AssertEx.SetEqual(new[] {
"Object, System, AssemblyReference:corlib",
"ValueTuple`2, System, AssemblyReference:" + appRef // ValueTuple comes from app, not corlib
},
reader.DumpTypeReferences());
}
}
[Fact]
public void TupleElementNamesAttribute_NotAvailable()
{
var source =
@"namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 _1, T2 _2)
{
Item1 = _1;
Item2 = _2;
}
}
}
class C
{
static void M()
{
(int, int) o;
}
}";
var comp = CreateCompilationWithMscorlib40(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
var result = context.CompileExpression("(A: 1, B: 2)", out error, testData);
Assert.Null(error);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
Assert.Null(customTypeInfo);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
Assert.True(method.ReturnType.IsTupleType);
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@" {
// Code size 8 (0x8)
.maxstack 2
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldc.i4.1
IL_0001: ldc.i4.2
IL_0002: newobj ""System.ValueTuple<int, int>..ctor(int, int)""
IL_0007: ret
}");
});
}
[Fact]
public void Local()
{
var source =
@"class C
{
static void M()
{
(int A\u1234, int \u1234B) o = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { "A\u1234", "\u1234B" }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
Assert.True(method.ReturnType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "o", expectedILOpt:
string.Format(@"{{
// Code size 2 (0x2)
.maxstack 1
.locals init (System.ValueTuple<int, int> V_0) //o
IL_0000: ldloc.0
IL_0001: ret
}}", '\u1234'));
locals.Free();
});
}
[Fact]
public void Constant()
{
var source =
@"class A<T>
{
internal class B<U>
{
}
}
class C
{
static (object, object) F;
static void M()
{
const A<(int, int A)>.B<(object B, object)>[] c = null;
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var assembly = context.CompileGetLocals(locals, argumentsOnly: false, typeName: out typeName, testData: testData);
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(new[] { null, "A", "B", null }, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(returnType.ContainsTuple());
VerifyLocal(testData, typeName, locals[0], "<>m0", "c", expectedFlags: DkmClrCompilationResultFlags.ReadOnlyResult, expectedILOpt:
@"{
// Code size 2 (0x2)
.maxstack 1
IL_0000: ldnull
IL_0001: ret
}");
locals.Free();
});
}
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
[Fact]
public void LongTupleLocalElement_NoNames()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, 3, 4, 5, 6, 7, 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item4 + x.Item8", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 19 (0x13)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Item4""
IL_0006: ldloc.0
IL_0007: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_000c: ldfld ""int System.ValueTuple<int>.Item1""
IL_0011: add
IL_0012: ret
}");
});
}
[Fact]
public void LongTupleLocalElement_Names()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2, Three: 3, Four: 4, 5, 6, 7, Eight: 8);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
context.CompileExpression("x.Item8 + x.Eight", out error, testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 24 (0x18)
.maxstack 2
.locals init (System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>> V_0) //x
IL_0000: ldloc.0
IL_0001: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0006: ldfld ""int System.ValueTuple<int>.Item1""
IL_000b: ldloc.0
IL_000c: ldfld ""System.ValueTuple<int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int>>.Rest""
IL_0011: ldfld ""int System.ValueTuple<int>.Item1""
IL_0016: add
IL_0017: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
public void DeclareLocal()
{
var source =
@"class C
{
static void M()
{
var x = (1, 2);
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var testData = new CompilationTestData();
string error;
ResultProperties resultProperties;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var result = context.CompileExpression(
"(int A, int B) y = x;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Equal(resultProperties.Flags, DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = result.GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Null(tupleElementNames);
var methodData = testData.GetMethodData("<>x.<>m0");
var method = (MethodSymbol)methodData.Method;
CheckAttribute(result.Assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: false);
methodData.VerifyIL(
@"{
// Code size 64 (0x40)
.maxstack 6
.locals init (System.ValueTuple<int, int> V_0) //x
IL_0000: ldtoken ""System.ValueTuple<int, int>""
IL_0005: call ""System.Type System.Type.GetTypeFromHandle(System.RuntimeTypeHandle)""
IL_000a: ldstr ""y""
IL_000f: ldstr ""108766ce-df68-46ee-b761-0dcb7ac805f1""
IL_0014: newobj ""System.Guid..ctor(string)""
IL_0019: ldc.i4.5
IL_001a: newarr ""byte""
IL_001f: dup
IL_0020: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=5 <PrivateImplementationDetails>.845151BC3876B3B783409FD71AF3665D783D8036161B4A2D2ACD27E1A0FCEDF7""
IL_0025: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)""
IL_002a: call ""void Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.CreateVariable(System.Type, string, System.Guid, byte[])""
IL_002f: ldstr ""y""
IL_0034: call ""System.ValueTuple<int, int> Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetVariableAddress<System.ValueTuple<int, int>>(string)""
IL_0039: ldloc.0
IL_003a: stobj ""System.ValueTuple<int, int>""
IL_003f: ret
}");
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13589, "https://github.com/dotnet/roslyn/issues/13589")]
public void AliasElement()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { ValueTupleRef, SystemRuntimeFacadeRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { ValueTupleRef, SystemRuntimeFacadeRef, MscorlibRef }, runtime =>
{
var context = CreateMethodContext(
runtime,
"C.M");
// (int A, (int, int D) B)[] t;
var aliasElementNames = new ReadOnlyCollection<string>(new[] { "A", "B", null, "D" });
var alias = new Alias(
DkmClrAliasKind.Variable,
"t",
"t",
"System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.ValueTuple`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]][], System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
CustomTypeInfo.PayloadTypeId,
CustomTypeInfo.Encode(null, aliasElementNames));
var locals = ArrayBuilder<LocalAndMethod>.GetInstance();
string typeName;
var diagnostics = DiagnosticBag.GetInstance();
var testData = new CompilationTestData();
var assembly = context.CompileGetLocals(
locals,
argumentsOnly: false,
aliases: ImmutableArray.Create(alias),
diagnostics: diagnostics,
typeName: out typeName,
testData: testData);
diagnostics.Verify();
diagnostics.Free();
Assert.Equal(1, locals.Count);
ReadOnlyCollection<byte> customTypeInfo;
var customTypeInfoId = locals[0].GetCustomTypeInfo(out customTypeInfo);
ReadOnlyCollection<byte> dynamicFlags;
ReadOnlyCollection<string> tupleElementNames;
CustomTypeInfo.Decode(customTypeInfoId, customTypeInfo, out dynamicFlags, out tupleElementNames);
Assert.Equal(aliasElementNames, tupleElementNames);
var method = (MethodSymbol)testData.GetExplicitlyDeclaredMethods().Single().Value.Method;
CheckAttribute(assembly, method, AttributeDescription.TupleElementNamesAttribute, expected: true);
var returnType = (TypeSymbol)method.ReturnType;
Assert.False(returnType.IsTupleType);
Assert.True(((ArrayTypeSymbol)returnType).ElementType.IsTupleType);
VerifyLocal(testData, typeName, locals[0], "<>m0", "t", expectedILOpt:
@"{
// Code size 16 (0x10)
.maxstack 1
IL_0000: ldstr ""t""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: castclass ""System.ValueTuple<int, System.ValueTuple<int, int>>[]""
IL_000f: ret
}");
locals.Free();
});
}
[ConditionalFact(typeof(IsRelease), Reason = "https://github.com/dotnet/roslyn/issues/25702")]
[WorkItem(13803, "https://github.com/dotnet/roslyn/issues/13803")]
public void AliasElement_NoNames()
{
var source =
@"class C
{
static (int, int) F;
static void M()
{
}
}";
var comp = CreateCompilationWithMscorlib40(source, new[] { SystemRuntimeFacadeRef, ValueTupleRef }, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, new[] { MscorlibRef, SystemCoreRef, SystemRuntimeFacadeRef, ValueTupleRef }, runtime =>
{
var context = CreateMethodContext(runtime, "C.M");
var alias = new Alias(
DkmClrAliasKind.Variable,
"x",
"x",
"System.ValueTuple`8[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.ValueTuple`2[" +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]," +
"[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51]], " +
"System.ValueTuple, Version=4.0.1.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51",
Guid.Empty,
null);
ResultProperties resultProperties;
string error;
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
var testData = new CompilationTestData();
context.CompileExpression(
"x.Item4 + x.Item8",
DkmEvaluationFlags.TreatAsExpression,
ImmutableArray.Create(alias),
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
null,
testData);
testData.GetMethodData("<>x.<>m0").VerifyIL(
@"{
// Code size 47 (0x2f)
.maxstack 2
IL_0000: ldstr ""x""
IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_000a: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_000f: ldfld ""int System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Item4""
IL_0014: ldstr ""x""
IL_0019: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)""
IL_001e: unbox.any ""System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>""
IL_0023: ldfld ""System.ValueTuple<int, int> System.ValueTuple<int, int, int, int, int, int, int, System.ValueTuple<int, int>>.Rest""
IL_0028: ldfld ""int System.ValueTuple<int, int>.Item1""
IL_002d: add
IL_002e: ret
}");
});
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/VisualBasicTest/ChangeSignature/AddParameterTests.OptionalParameter.Omit.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.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_ToEmptySignature_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$()
M()
End Sub
End Class]]></Text>.NormalizedValue()
Dim updatedSignature As AddedParameterOrExistingIndex() = {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(Optional a As Integer = 1)
M()
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$(x As Integer)
M(1)
End Sub
End Class]]></Text>.NormalizedValue()
Dim updatedSignature As AddedParameterOrExistingIndex() = {
New AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(x As Integer, Optional a As Integer = 1)
M(1)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$(Optional x As Integer = 2)
M()
M(2)
M(x:=2)
End Sub
End Class]]></Text>.NormalizedValue()
Dim updatedSignature As AddedParameterOrExistingIndex() = {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"),
New AddedParameterOrExistingIndex(0)}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(Optional a As Integer = 1, Optional x As Integer = 2)
M()
M(x:=2)
M(x:=2)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$(ParamArray p As Integer())
M()
M(1)
M(1, 2)
M(1, 2, 3)
End Sub
End Class]]></Text>.NormalizedValue()
' This is an illegal configuration in VB, but can happen if cascaded from the legal C#
' version of this configuration. We reinterpret OMIT as TODO in this case.
Dim updatedSignature As AddedParameterOrExistingIndex() = {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"),
New AddedParameterOrExistingIndex(0)}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(Optional a As Integer = 1, ParamArray p As Integer())
M(TODO)
M(TODO, 1)
M(TODO, 1, 2)
M(TODO, 1, 2, 3)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() As Task
Dim markup = <Text><![CDATA[
<Some(1, 2, 4)>
Class SomeAttribute
Inherits System.Attribute
Sub New$$(a As Integer, b As Integer, Optional y As Integer = 4)
End Sub
End Class]]></Text>.NormalizedValue()
Dim permutation = {
New AddedParameterOrExistingIndex(0),
New AddedParameterOrExistingIndex(1),
AddedParameterOrExistingIndex.CreateAdded("Integer", "x", CallSiteKind.Omitted, isRequired:=False, defaultValue:="3"),
New AddedParameterOrExistingIndex(2)}
Dim updatedCode = <Text><![CDATA[
<Some(1, 2, y:=4)>
Class SomeAttribute
Inherits System.Attribute
Sub New(a As Integer, b As Integer, Optional x As Integer = 3, Optional y As Integer = 4)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode)
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.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ChangeSignature
Partial Public Class ChangeSignatureTests
Inherits AbstractChangeSignatureTests
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_ToEmptySignature_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$()
M()
End Sub
End Class]]></Text>.NormalizedValue()
Dim updatedSignature As AddedParameterOrExistingIndex() = {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(Optional a As Integer = 1)
M()
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_AfterRequiredParameter_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$(x As Integer)
M(1)
End Sub
End Class]]></Text>.NormalizedValue()
Dim updatedSignature As AddedParameterOrExistingIndex() = {
New AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1")}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(x As Integer, Optional a As Integer = 1)
M(1)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_BeforeOptionalParameter_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$(Optional x As Integer = 2)
M()
M(2)
M(x:=2)
End Sub
End Class]]></Text>.NormalizedValue()
Dim updatedSignature As AddedParameterOrExistingIndex() = {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"),
New AddedParameterOrExistingIndex(0)}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(Optional a As Integer = 1, Optional x As Integer = 2)
M()
M(x:=2)
M(x:=2)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameter_BeforeExpandedParamsArray_CallsiteOmitted() As Task
Dim markup = <Text><![CDATA[
Class C
Sub M$$(ParamArray p As Integer())
M()
M(1)
M(1, 2)
M(1, 2, 3)
End Sub
End Class]]></Text>.NormalizedValue()
' This is an illegal configuration in VB, but can happen if cascaded from the legal C#
' version of this configuration. We reinterpret OMIT as TODO in this case.
Dim updatedSignature As AddedParameterOrExistingIndex() = {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Omitted, isRequired:=False, defaultValue:="1"),
New AddedParameterOrExistingIndex(0)}
Dim updatedCode = <Text><![CDATA[
Class C
Sub M(Optional a As Integer = 1, ParamArray p As Integer())
M(TODO)
M(TODO, 1)
M(TODO, 1, 2)
M(TODO, 1, 2, 3)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=updatedSignature, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.ChangeSignature)>
Public Async Function AddOptionalParameterWithOmittedCallsiteToAttributeConstructor() As Task
Dim markup = <Text><![CDATA[
<Some(1, 2, 4)>
Class SomeAttribute
Inherits System.Attribute
Sub New$$(a As Integer, b As Integer, Optional y As Integer = 4)
End Sub
End Class]]></Text>.NormalizedValue()
Dim permutation = {
New AddedParameterOrExistingIndex(0),
New AddedParameterOrExistingIndex(1),
AddedParameterOrExistingIndex.CreateAdded("Integer", "x", CallSiteKind.Omitted, isRequired:=False, defaultValue:="3"),
New AddedParameterOrExistingIndex(2)}
Dim updatedCode = <Text><![CDATA[
<Some(1, 2, y:=4)>
Class SomeAttribute
Inherits System.Attribute
Sub New(a As Integer, b As Integer, Optional x As Integer = 3, Optional y As Integer = 4)
End Sub
End Class]]></Text>.NormalizedValue()
Await TestChangeSignatureViaCommandAsync(LanguageNames.VisualBasic, markup, updatedSignature:=permutation, expectedUpdatedInvocationDocumentCode:=updatedCode)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundAwaitOperator.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundAwaitOperator
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Type.Equals(GetResult.Type) OrElse Type.SpecialType = SpecialType.System_Void)
End Sub
#End If
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
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundAwaitOperator
#If DEBUG Then
Private Sub Validate()
Debug.Assert(Type.Equals(GetResult.Type) OrElse Type.SpecialType = SpecialType.System_Void)
End Sub
#End If
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/ExpressionEvaluator/Core/Test/FunctionResolver/TypeComparer.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;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
{
internal sealed class TypeComparer : IEqualityComparer<TypeSignature>
{
internal static readonly TypeComparer Instance = new TypeComparer();
public bool Equals(TypeSignature x, TypeSignature y)
{
if (x == null)
{
return y == null;
}
if (y == null)
{
return false;
}
if (x.Kind != y.Kind)
{
return false;
}
switch (x.Kind)
{
case TypeSignatureKind.QualifiedType:
{
var xQualified = (QualifiedTypeSignature)x;
var yQualified = (QualifiedTypeSignature)y;
return Equals(xQualified.Qualifier, yQualified.Qualifier) &&
Equals(xQualified.Name, yQualified.Name);
}
case TypeSignatureKind.GenericType:
{
var xGeneric = (GenericTypeSignature)x;
var yGeneric = (GenericTypeSignature)y;
return Equals(xGeneric.QualifiedName, yGeneric.QualifiedName) &&
xGeneric.TypeArguments.SequenceEqual(yGeneric.TypeArguments, this);
}
case TypeSignatureKind.ArrayType:
{
var xArray = (ArrayTypeSignature)x;
var yArray = (ArrayTypeSignature)y;
return Equals(xArray.ElementType, yArray.ElementType) &&
xArray.Rank == yArray.Rank;
}
case TypeSignatureKind.PointerType:
{
var xPointer = (PointerTypeSignature)x;
var yPointer = (PointerTypeSignature)y;
return Equals(xPointer.PointedAtType, yPointer.PointedAtType);
}
default:
throw new NotImplementedException();
}
}
public int GetHashCode(TypeSignature obj)
{
throw new NotImplementedException();
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
namespace Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests
{
internal sealed class TypeComparer : IEqualityComparer<TypeSignature>
{
internal static readonly TypeComparer Instance = new TypeComparer();
public bool Equals(TypeSignature x, TypeSignature y)
{
if (x == null)
{
return y == null;
}
if (y == null)
{
return false;
}
if (x.Kind != y.Kind)
{
return false;
}
switch (x.Kind)
{
case TypeSignatureKind.QualifiedType:
{
var xQualified = (QualifiedTypeSignature)x;
var yQualified = (QualifiedTypeSignature)y;
return Equals(xQualified.Qualifier, yQualified.Qualifier) &&
Equals(xQualified.Name, yQualified.Name);
}
case TypeSignatureKind.GenericType:
{
var xGeneric = (GenericTypeSignature)x;
var yGeneric = (GenericTypeSignature)y;
return Equals(xGeneric.QualifiedName, yGeneric.QualifiedName) &&
xGeneric.TypeArguments.SequenceEqual(yGeneric.TypeArguments, this);
}
case TypeSignatureKind.ArrayType:
{
var xArray = (ArrayTypeSignature)x;
var yArray = (ArrayTypeSignature)y;
return Equals(xArray.ElementType, yArray.ElementType) &&
xArray.Rank == yArray.Rank;
}
case TypeSignatureKind.PointerType:
{
var xPointer = (PointerTypeSignature)x;
var yPointer = (PointerTypeSignature)y;
return Equals(xPointer.PointedAtType, yPointer.PointedAtType);
}
default:
throw new NotImplementedException();
}
}
public int GetHashCode(TypeSignature obj)
{
throw new NotImplementedException();
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Symbol/Symbols/TypeResolutionTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
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 Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class TypeResolutionTests : CSharpTestBase
{
[Fact]
public void TestGetTypeByNameAndArity()
{
string source1 = @"
namespace System
{
public class TestClass
{
}
public class TestClass<T>
{
}
}
";
string source2 = @"
namespace System
{
public class TestClass
{
}
}
";
var c1 = CSharpCompilation.Create("Test1",
syntaxTrees: new[] { Parse(source1) },
references: new[] { Net40.mscorlib });
Assert.Null(c1.GetTypeByMetadataName("DoesntExist"));
Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1"));
Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2"));
NamedTypeSymbol c1TestClass = c1.GetTypeByMetadataName("System.TestClass");
Assert.NotNull(c1TestClass);
NamedTypeSymbol c1TestClassT = c1.GetTypeByMetadataName("System.TestClass`1");
Assert.NotNull(c1TestClassT);
Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2"));
var c2 = CSharpCompilation.Create("Test2",
syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(source2) },
references: new MetadataReference[]
{
new CSharpCompilationReference(c1),
Net40.mscorlib
});
NamedTypeSymbol c2TestClass = c2.GetTypeByMetadataName("System.TestClass");
Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly);
var c3 = CSharpCompilation.Create("Test3",
references: new MetadataReference[]
{
new CSharpCompilationReference(c2),
Net40.mscorlib
});
NamedTypeSymbol c3TestClass = c3.GetTypeByMetadataName("System.TestClass");
Assert.NotSame(c2TestClass, c3TestClass);
Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly));
Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1"));
var c4 = CSharpCompilation.Create("Test4",
references: new MetadataReference[]
{
new CSharpCompilationReference(c1),
new CSharpCompilationReference(c2),
Net40.mscorlib
});
NamedTypeSymbol c4TestClass = c4.GetTypeByMetadataName("System.TestClass");
Assert.Null(c4TestClass);
Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`1"));
}
public class C<S, T>
{
public class D
{
public class E<U, V>
{
public class F<W>
{
}
}
}
}
[ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))]
public void TypeSymbolFromReflectionType()
{
var c = CSharpCompilation.Create("TypeSymbolFromReflectionType",
syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree("class C { }") },
references: new[] {
MscorlibRef,
MetadataReference.CreateFromImage(File.ReadAllBytes(typeof(TypeTests).GetTypeInfo().Assembly.Location))
});
var intSym = c.Assembly.GetTypeByReflectionType(typeof(int), includeReferences: true);
Assert.NotNull(intSym);
Assert.Equal(SpecialType.System_Int32, intSym.SpecialType);
var strcmpSym = c.Assembly.GetTypeByReflectionType(typeof(StringComparison), includeReferences: true);
Assert.NotNull(strcmpSym);
Assert.Equal("System.StringComparison", strcmpSym.ToDisplayString());
var arraySym = c.Assembly.GetTypeByReflectionType(typeof(List<int>[][,,]), includeReferences: true);
Assert.NotNull(arraySym);
Assert.Equal("System.Collections.Generic.List<int>[][*,*,*]", arraySym.ToDisplayString());
var ptrSym = c.Assembly.GetTypeByReflectionType(typeof(char).MakePointerType().MakePointerType(), includeReferences: true);
Assert.NotNull(ptrSym);
Assert.Equal("char**", ptrSym.ToDisplayString());
string testType1 = typeof(C<,>).DeclaringType.FullName;
var nestedSym1 = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, float>.F<byte>), includeReferences: true);
Assert.Equal(testType1 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym1.ToDisplayString());
// Not supported atm:
//string testType2 = typeof(C<,>).DeclaringType.FullName;
//var nestedSym2 = c.Assembly.GetTypeByReflectionType(typeof(C<,>.D.E<,>.F<>), includeReferences: true);
//Assert.Equal(testType2 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym2.ToDisplayString());
// Process is defined in System, which isn't referenced:
var err = c.Assembly.GetTypeByReflectionType(typeof(C<Process, bool>.D.E<double, float>.F<byte>), includeReferences: true);
Assert.Null(err);
err = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, Process>.F<byte>), includeReferences: true);
Assert.Null(err);
err = c.Assembly.GetTypeByReflectionType(typeof(Process[]), includeReferences: true);
Assert.Null(err);
err = c.Assembly.GetTypeByReflectionType(typeof(SyntaxKind).MakePointerType(), includeReferences: true);
Assert.Null(err);
}
[Fact]
public void AmbiguousNestedTypeSymbolFromMetadata()
{
var code = "class A { class B { } }";
var c1 = CSharpCompilation.Create("Asm1", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) });
var c2 = CSharpCompilation.Create("Asm2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) });
var c3 = CSharpCompilation.Create("Asm3",
references: new[] {
new CSharpCompilationReference(c1),
new CSharpCompilationReference(c2)
});
Assert.Null(c3.GetTypeByMetadataName("A+B"));
}
[Fact]
public void DuplicateNestedTypeSymbol()
{
var code = "class A { class B { } class B { } }";
var c1 = CSharpCompilation.Create("Asm1",
syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) });
Assert.Equal("A.B", c1.GetTypeByMetadataName("A+B").ToTestDisplayString());
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
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 Roslyn.Utilities;
using Xunit;
using static Roslyn.Test.Utilities.TestMetadata;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Symbols
{
public class TypeResolutionTests : CSharpTestBase
{
[Fact]
public void TestGetTypeByNameAndArity()
{
string source1 = @"
namespace System
{
public class TestClass
{
}
public class TestClass<T>
{
}
}
";
string source2 = @"
namespace System
{
public class TestClass
{
}
}
";
var c1 = CSharpCompilation.Create("Test1",
syntaxTrees: new[] { Parse(source1) },
references: new[] { Net40.mscorlib });
Assert.Null(c1.GetTypeByMetadataName("DoesntExist"));
Assert.Null(c1.GetTypeByMetadataName("DoesntExist`1"));
Assert.Null(c1.GetTypeByMetadataName("DoesntExist`2"));
NamedTypeSymbol c1TestClass = c1.GetTypeByMetadataName("System.TestClass");
Assert.NotNull(c1TestClass);
NamedTypeSymbol c1TestClassT = c1.GetTypeByMetadataName("System.TestClass`1");
Assert.NotNull(c1TestClassT);
Assert.Null(c1.GetTypeByMetadataName("System.TestClass`2"));
var c2 = CSharpCompilation.Create("Test2",
syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(source2) },
references: new MetadataReference[]
{
new CSharpCompilationReference(c1),
Net40.mscorlib
});
NamedTypeSymbol c2TestClass = c2.GetTypeByMetadataName("System.TestClass");
Assert.Same(c2.Assembly, c2TestClass.ContainingAssembly);
var c3 = CSharpCompilation.Create("Test3",
references: new MetadataReference[]
{
new CSharpCompilationReference(c2),
Net40.mscorlib
});
NamedTypeSymbol c3TestClass = c3.GetTypeByMetadataName("System.TestClass");
Assert.NotSame(c2TestClass, c3TestClass);
Assert.True(c3TestClass.ContainingAssembly.RepresentsTheSameAssemblyButHasUnresolvedReferencesByComparisonTo(c2TestClass.ContainingAssembly));
Assert.Null(c3.GetTypeByMetadataName("System.TestClass`1"));
var c4 = CSharpCompilation.Create("Test4",
references: new MetadataReference[]
{
new CSharpCompilationReference(c1),
new CSharpCompilationReference(c2),
Net40.mscorlib
});
NamedTypeSymbol c4TestClass = c4.GetTypeByMetadataName("System.TestClass");
Assert.Null(c4TestClass);
Assert.Same(c1TestClassT, c4.GetTypeByMetadataName("System.TestClass`1"));
}
public class C<S, T>
{
public class D
{
public class E<U, V>
{
public class F<W>
{
}
}
}
}
[ConditionalFact(typeof(ClrOnly), typeof(DesktopOnly))]
public void TypeSymbolFromReflectionType()
{
var c = CSharpCompilation.Create("TypeSymbolFromReflectionType",
syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree("class C { }") },
references: new[] {
MscorlibRef,
MetadataReference.CreateFromImage(File.ReadAllBytes(typeof(TypeTests).GetTypeInfo().Assembly.Location))
});
var intSym = c.Assembly.GetTypeByReflectionType(typeof(int), includeReferences: true);
Assert.NotNull(intSym);
Assert.Equal(SpecialType.System_Int32, intSym.SpecialType);
var strcmpSym = c.Assembly.GetTypeByReflectionType(typeof(StringComparison), includeReferences: true);
Assert.NotNull(strcmpSym);
Assert.Equal("System.StringComparison", strcmpSym.ToDisplayString());
var arraySym = c.Assembly.GetTypeByReflectionType(typeof(List<int>[][,,]), includeReferences: true);
Assert.NotNull(arraySym);
Assert.Equal("System.Collections.Generic.List<int>[][*,*,*]", arraySym.ToDisplayString());
var ptrSym = c.Assembly.GetTypeByReflectionType(typeof(char).MakePointerType().MakePointerType(), includeReferences: true);
Assert.NotNull(ptrSym);
Assert.Equal("char**", ptrSym.ToDisplayString());
string testType1 = typeof(C<,>).DeclaringType.FullName;
var nestedSym1 = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, float>.F<byte>), includeReferences: true);
Assert.Equal(testType1 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym1.ToDisplayString());
// Not supported atm:
//string testType2 = typeof(C<,>).DeclaringType.FullName;
//var nestedSym2 = c.Assembly.GetTypeByReflectionType(typeof(C<,>.D.E<,>.F<>), includeReferences: true);
//Assert.Equal(testType2 + ".C<int, bool>.D.E<double, float>.F<byte>", nestedSym2.ToDisplayString());
// Process is defined in System, which isn't referenced:
var err = c.Assembly.GetTypeByReflectionType(typeof(C<Process, bool>.D.E<double, float>.F<byte>), includeReferences: true);
Assert.Null(err);
err = c.Assembly.GetTypeByReflectionType(typeof(C<int, bool>.D.E<double, Process>.F<byte>), includeReferences: true);
Assert.Null(err);
err = c.Assembly.GetTypeByReflectionType(typeof(Process[]), includeReferences: true);
Assert.Null(err);
err = c.Assembly.GetTypeByReflectionType(typeof(SyntaxKind).MakePointerType(), includeReferences: true);
Assert.Null(err);
}
[Fact]
public void AmbiguousNestedTypeSymbolFromMetadata()
{
var code = "class A { class B { } }";
var c1 = CSharpCompilation.Create("Asm1", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) });
var c2 = CSharpCompilation.Create("Asm2", syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) });
var c3 = CSharpCompilation.Create("Asm3",
references: new[] {
new CSharpCompilationReference(c1),
new CSharpCompilationReference(c2)
});
Assert.Null(c3.GetTypeByMetadataName("A+B"));
}
[Fact]
public void DuplicateNestedTypeSymbol()
{
var code = "class A { class B { } class B { } }";
var c1 = CSharpCompilation.Create("Asm1",
syntaxTrees: new[] { SyntaxFactory.ParseSyntaxTree(code) });
Assert.Equal("A.B", c1.GetTypeByMetadataName("A+B").ToTestDisplayString());
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/Core/Def/ExternalAccess/ProjectSystem/Api/IProjectSystemReferenceCleanupService2.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
// Interface to be implemented and MEF exported by Project System
internal interface IProjectSystemReferenceCleanupService2 : IProjectSystemReferenceCleanupService
{
/// <summary>
/// Gets an operation that can update the projectโs references by removing or marking references as
/// TreatAsUsed in the project file.
/// </summary>
Task<IProjectSystemUpdateReferenceOperation> GetUpdateReferenceOperationAsync(
string projectPath,
ProjectSystemReferenceUpdate referenceUpdate,
CancellationToken canellationToken);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.ExternalAccess.ProjectSystem.Api
{
// Interface to be implemented and MEF exported by Project System
internal interface IProjectSystemReferenceCleanupService2 : IProjectSystemReferenceCleanupService
{
/// <summary>
/// Gets an operation that can update the projectโs references by removing or marking references as
/// TreatAsUsed in the project file.
/// </summary>
Task<IProjectSystemUpdateReferenceOperation> GetUpdateReferenceOperationAsync(
string projectPath,
ProjectSystemReferenceUpdate referenceUpdate,
CancellationToken canellationToken);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Features/Core/Portable/CodeRefactorings/MoveType/IMoveTypeService.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
internal interface IMoveTypeService : ILanguageService
{
Task<ImmutableArray<CodeAction>> GetRefactoringAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeRefactorings.MoveType
{
internal interface IMoveTypeService : ILanguageService
{
Task<ImmutableArray<CodeAction>> GetRefactoringAsync(Document document, TextSpan textSpan, CancellationToken cancellationToken);
Task<Solution> GetModifiedSolutionAsync(Document document, TextSpan textSpan, MoveTypeOperationKind operationKind, CancellationToken cancellationToken);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Analysis/FlowAnalysis/DataFlowPass.Symbols.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class DataFlowPass
''' <summary>
''' AmbiguousLocalsPseudoSymbol is a pseudo-symbol used in flow analysis representing
''' a symbol of the implicit receiver in case Dim statement defines more than one variable,
''' but uses the same object initializer for all of them, like:
''' Dim a,b As New C() With { .X = .Y }
''' </summary>
Protected NotInheritable Class AmbiguousLocalsPseudoSymbol
Inherits LocalSymbol
Public ReadOnly Locals As ImmutableArray(Of LocalSymbol)
Private Sub New(container As Symbol, type As TypeSymbol, locals As ImmutableArray(Of LocalSymbol))
MyBase.New(container, type)
Debug.Assert(type IsNot Nothing)
Me.Locals = locals
End Sub
Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind
Get
Return LocalDeclarationKind.AmbiguousLocals
End Get
End Property
Friend Overrides ReadOnly Property SynthesizedKind As SynthesizedLocalKind
Get
Return SynthesizedLocalKind.UserDefined
End Get
End Property
Public Overrides ReadOnly Property IsFunctionValue As Boolean
Get
Return False
End Get
End Property
Friend Shared Shadows Function Create(locals As ImmutableArray(Of LocalSymbol)) As LocalSymbol
Debug.Assert(Not locals.IsDefault AndAlso locals.Length > 1)
Dim firstLocal As LocalSymbol = locals(0)
Return New AmbiguousLocalsPseudoSymbol(firstLocal.ContainingSymbol, firstLocal.Type, locals)
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Friend Overrides Function GetDeclaratorSyntax() As SyntaxNode
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IdentifierLocation As Location
Get
Return NoLocation.Singleton
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IsByRef As Boolean
Get
Return False
End Get
End Property
End Class
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class DataFlowPass
''' <summary>
''' AmbiguousLocalsPseudoSymbol is a pseudo-symbol used in flow analysis representing
''' a symbol of the implicit receiver in case Dim statement defines more than one variable,
''' but uses the same object initializer for all of them, like:
''' Dim a,b As New C() With { .X = .Y }
''' </summary>
Protected NotInheritable Class AmbiguousLocalsPseudoSymbol
Inherits LocalSymbol
Public ReadOnly Locals As ImmutableArray(Of LocalSymbol)
Private Sub New(container As Symbol, type As TypeSymbol, locals As ImmutableArray(Of LocalSymbol))
MyBase.New(container, type)
Debug.Assert(type IsNot Nothing)
Me.Locals = locals
End Sub
Friend Overrides ReadOnly Property DeclarationKind As LocalDeclarationKind
Get
Return LocalDeclarationKind.AmbiguousLocals
End Get
End Property
Friend Overrides ReadOnly Property SynthesizedKind As SynthesizedLocalKind
Get
Return SynthesizedLocalKind.UserDefined
End Get
End Property
Public Overrides ReadOnly Property IsFunctionValue As Boolean
Get
Return False
End Get
End Property
Friend Shared Shadows Function Create(locals As ImmutableArray(Of LocalSymbol)) As LocalSymbol
Debug.Assert(Not locals.IsDefault AndAlso locals.Length > 1)
Dim firstLocal As LocalSymbol = locals(0)
Return New AmbiguousLocalsPseudoSymbol(firstLocal.ContainingSymbol, firstLocal.Type, locals)
End Function
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray(Of Location).Empty
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray(Of SyntaxReference).Empty
End Get
End Property
Friend Overrides Function GetDeclaratorSyntax() As SyntaxNode
Throw ExceptionUtilities.Unreachable
End Function
Friend Overrides ReadOnly Property IdentifierToken As SyntaxToken
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IdentifierLocation As Location
Get
Return NoLocation.Singleton
End Get
End Property
Public Overrides ReadOnly Property Name As String
Get
Return Nothing
End Get
End Property
Friend Overrides ReadOnly Property IsByRef As Boolean
Get
Return False
End Get
End Property
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest2/Recommendations/UncheckedKeywordRecommenderTests.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 UncheckedKeywordRecommenderTests : 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 TestEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInDefault()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInSizeOf()
{
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 UncheckedKeywordRecommenderTests : 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 TestEmptyStatement()
{
await VerifyKeywordAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInExpression()
{
await VerifyKeywordAsync(AddInsideMethod(
@"var q = $$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInTypeOf()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"typeof($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInDefault()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"default($$"));
}
[WorkItem(538804, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538804")]
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInSizeOf()
{
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 | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/VisualBasic/Portable/Syntax/ArrayRankSpecifierSyntax.vb | ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class ArrayRankSpecifierSyntax
''' <summary>
''' Returns the ranks of this array rank specifier.
''' </summary>
Public ReadOnly Property Rank() As Integer
Get
Return Me.CommaTokens.Count + 1
End Get
End Property
End Class
End Namespace
| ๏ปฟ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax
Partial Public Class ArrayRankSpecifierSyntax
''' <summary>
''' Returns the ranks of this array rank specifier.
''' </summary>
Public ReadOnly Property Rank() As Integer
Get
Return Me.CommaTokens.Count + 1
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/Core/Portable/SignatureComparer.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RuntimeMembers
{
/// <summary>
/// Helper class to match signatures in format of
/// MemberDescriptor.Signature to members.
/// </summary>
internal abstract class SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol>
where MethodSymbol : class
where FieldSymbol : class
where PropertySymbol : class
where TypeSymbol : class
where ParameterSymbol : class
{
/// <summary>
/// Returns true if signature matches signature of the field.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchFieldSignature(FieldSymbol field, ImmutableArray<byte> signature)
{
int position = 0;
// get the type
bool result = MatchType(GetFieldType(field), signature, ref position);
Debug.Assert(!result || position == signature.Length);
return result;
}
/// <summary>
/// Returns true if signature matches signature of the property.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchPropertySignature(PropertySymbol property, ImmutableArray<byte> signature)
{
int position = 0;
// Get the parameter count
int paramCount = signature[position++];
// Get all of the parameters.
ImmutableArray<ParameterSymbol> parameters = GetParameters(property);
if (paramCount != parameters.Length)
{
return false;
}
bool isByRef = IsByRef(signature, ref position);
if (IsByRefProperty(property) != isByRef)
{
return false;
}
// get the property type
if (!MatchType(GetPropertyType(property), signature, ref position))
{
return false;
}
// Match parameters
foreach (ParameterSymbol parameter in parameters)
{
if (!MatchParameter(parameter, signature, ref position))
{
return false;
}
}
Debug.Assert(position == signature.Length);
return true;
}
/// <summary>
/// Returns true if signature matches signature of the method.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchMethodSignature(MethodSymbol method, ImmutableArray<byte> signature)
{
int position = 0;
// Get the parameter count
int paramCount = signature[position++];
// Get all of the parameters.
ImmutableArray<ParameterSymbol> parameters = GetParameters(method);
if (paramCount != parameters.Length)
{
return false;
}
bool isByRef = IsByRef(signature, ref position);
if (IsByRefMethod(method) != isByRef)
{
return false;
}
// get the return type
if (!MatchType(GetReturnType(method), signature, ref position))
{
return false;
}
// Match parameters
foreach (ParameterSymbol parameter in parameters)
{
if (!MatchParameter(parameter, signature, ref position))
{
return false;
}
}
Debug.Assert(position == signature.Length);
return true;
}
private bool MatchParameter(ParameterSymbol parameter, ImmutableArray<byte> signature, ref int position)
{
bool isByRef = IsByRef(signature, ref position);
if (IsByRefParam(parameter) != isByRef)
{
return false;
}
return MatchType(GetParamType(parameter), signature, ref position);
}
private static bool IsByRef(ImmutableArray<byte> signature, ref int position)
{
SignatureTypeCode typeCode = (SignatureTypeCode)signature[position];
if (typeCode == SignatureTypeCode.ByReference)
{
position++;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Does pretty much the same thing as MetadataDecoder.DecodeType only instead of
/// producing a type symbol it compares encoded type to the target.
///
/// Signature should be in format described in MemberDescriptor.
/// </summary>
private bool MatchType(TypeSymbol? type, ImmutableArray<byte> signature, ref int position)
{
if (type == null)
{
return false;
}
int paramPosition;
// Get the type.
SignatureTypeCode typeCode = (SignatureTypeCode)signature[position++];
// Switch on the type.
switch (typeCode)
{
case SignatureTypeCode.TypeHandle:
// Ecma-335 spec:
// 23.1.16 Element types used in signatures
// ...
// ELEMENT_TYPE_VALUETYPE 0x11 Followed by TypeDef or TypeRef token
// ELEMENT_TYPE_CLASS 0x12 Followed by TypeDef or TypeRef token
short expectedType = ReadTypeId(signature, ref position);
return MatchTypeToTypeId(type, expectedType);
case SignatureTypeCode.Array:
if (!MatchType(GetMDArrayElementType(type), signature, ref position))
{
return false;
}
int countOfDimensions = signature[position++];
return MatchArrayRank(type, countOfDimensions);
case SignatureTypeCode.SZArray:
return MatchType(GetSZArrayElementType(type), signature, ref position);
case SignatureTypeCode.Pointer:
return MatchType(GetPointedToType(type), signature, ref position);
case SignatureTypeCode.GenericTypeParameter:
paramPosition = signature[position++];
return IsGenericTypeParam(type, paramPosition);
case SignatureTypeCode.GenericMethodParameter:
paramPosition = signature[position++];
return IsGenericMethodTypeParam(type, paramPosition);
case SignatureTypeCode.GenericTypeInstance:
if (!MatchType(GetGenericTypeDefinition(type), signature, ref position))
{
return false;
}
int argumentCount = signature[position++];
for (int argumentIndex = 0; argumentIndex < argumentCount; argumentIndex++)
{
if (!MatchType(GetGenericTypeArgument(type, argumentIndex), signature, ref position))
{
return false;
}
}
return true;
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
}
}
/// <summary>
/// Read a type Id from the signature.
/// This may consume one or two bytes, and therefore increment the position correspondingly.
/// </summary>
private static short ReadTypeId(ImmutableArray<byte> signature, ref int position)
{
var firstByte = signature[position++];
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
return (short)(signature[position++] + WellKnownType.ExtSentinel);
}
else
{
return firstByte;
}
}
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex);
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetGenericTypeDefinition(TypeSymbol type);
protected abstract bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition);
protected abstract bool IsGenericTypeParam(TypeSymbol type, int paramPosition);
/// <summary>
/// Should only accept Pointer types.
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetPointedToType(TypeSymbol type);
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetSZArrayElementType(TypeSymbol type);
/// <summary>
/// Should only accept multi-dimensional arrays.
/// </summary>
protected abstract bool MatchArrayRank(TypeSymbol type, int countOfDimensions);
/// <summary>
/// Should only accept multi-dimensional arrays.
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetMDArrayElementType(TypeSymbol type);
protected abstract bool MatchTypeToTypeId(TypeSymbol type, int typeId);
protected abstract TypeSymbol GetReturnType(MethodSymbol method);
protected abstract ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method);
protected abstract TypeSymbol GetPropertyType(PropertySymbol property);
protected abstract ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property);
protected abstract TypeSymbol GetParamType(ParameterSymbol parameter);
protected abstract bool IsByRefParam(ParameterSymbol parameter);
protected abstract bool IsByRefMethod(MethodSymbol method);
protected abstract bool IsByRefProperty(PropertySymbol property);
protected abstract TypeSymbol GetFieldType(FieldSymbol field);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Reflection.Metadata;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RuntimeMembers
{
/// <summary>
/// Helper class to match signatures in format of
/// MemberDescriptor.Signature to members.
/// </summary>
internal abstract class SignatureComparer<MethodSymbol, FieldSymbol, PropertySymbol, TypeSymbol, ParameterSymbol>
where MethodSymbol : class
where FieldSymbol : class
where PropertySymbol : class
where TypeSymbol : class
where ParameterSymbol : class
{
/// <summary>
/// Returns true if signature matches signature of the field.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchFieldSignature(FieldSymbol field, ImmutableArray<byte> signature)
{
int position = 0;
// get the type
bool result = MatchType(GetFieldType(field), signature, ref position);
Debug.Assert(!result || position == signature.Length);
return result;
}
/// <summary>
/// Returns true if signature matches signature of the property.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchPropertySignature(PropertySymbol property, ImmutableArray<byte> signature)
{
int position = 0;
// Get the parameter count
int paramCount = signature[position++];
// Get all of the parameters.
ImmutableArray<ParameterSymbol> parameters = GetParameters(property);
if (paramCount != parameters.Length)
{
return false;
}
bool isByRef = IsByRef(signature, ref position);
if (IsByRefProperty(property) != isByRef)
{
return false;
}
// get the property type
if (!MatchType(GetPropertyType(property), signature, ref position))
{
return false;
}
// Match parameters
foreach (ParameterSymbol parameter in parameters)
{
if (!MatchParameter(parameter, signature, ref position))
{
return false;
}
}
Debug.Assert(position == signature.Length);
return true;
}
/// <summary>
/// Returns true if signature matches signature of the method.
/// Signature should be in format described in MemberDescriptor.
/// </summary>
public bool MatchMethodSignature(MethodSymbol method, ImmutableArray<byte> signature)
{
int position = 0;
// Get the parameter count
int paramCount = signature[position++];
// Get all of the parameters.
ImmutableArray<ParameterSymbol> parameters = GetParameters(method);
if (paramCount != parameters.Length)
{
return false;
}
bool isByRef = IsByRef(signature, ref position);
if (IsByRefMethod(method) != isByRef)
{
return false;
}
// get the return type
if (!MatchType(GetReturnType(method), signature, ref position))
{
return false;
}
// Match parameters
foreach (ParameterSymbol parameter in parameters)
{
if (!MatchParameter(parameter, signature, ref position))
{
return false;
}
}
Debug.Assert(position == signature.Length);
return true;
}
private bool MatchParameter(ParameterSymbol parameter, ImmutableArray<byte> signature, ref int position)
{
bool isByRef = IsByRef(signature, ref position);
if (IsByRefParam(parameter) != isByRef)
{
return false;
}
return MatchType(GetParamType(parameter), signature, ref position);
}
private static bool IsByRef(ImmutableArray<byte> signature, ref int position)
{
SignatureTypeCode typeCode = (SignatureTypeCode)signature[position];
if (typeCode == SignatureTypeCode.ByReference)
{
position++;
return true;
}
else
{
return false;
}
}
/// <summary>
/// Does pretty much the same thing as MetadataDecoder.DecodeType only instead of
/// producing a type symbol it compares encoded type to the target.
///
/// Signature should be in format described in MemberDescriptor.
/// </summary>
private bool MatchType(TypeSymbol? type, ImmutableArray<byte> signature, ref int position)
{
if (type == null)
{
return false;
}
int paramPosition;
// Get the type.
SignatureTypeCode typeCode = (SignatureTypeCode)signature[position++];
// Switch on the type.
switch (typeCode)
{
case SignatureTypeCode.TypeHandle:
// Ecma-335 spec:
// 23.1.16 Element types used in signatures
// ...
// ELEMENT_TYPE_VALUETYPE 0x11 Followed by TypeDef or TypeRef token
// ELEMENT_TYPE_CLASS 0x12 Followed by TypeDef or TypeRef token
short expectedType = ReadTypeId(signature, ref position);
return MatchTypeToTypeId(type, expectedType);
case SignatureTypeCode.Array:
if (!MatchType(GetMDArrayElementType(type), signature, ref position))
{
return false;
}
int countOfDimensions = signature[position++];
return MatchArrayRank(type, countOfDimensions);
case SignatureTypeCode.SZArray:
return MatchType(GetSZArrayElementType(type), signature, ref position);
case SignatureTypeCode.Pointer:
return MatchType(GetPointedToType(type), signature, ref position);
case SignatureTypeCode.GenericTypeParameter:
paramPosition = signature[position++];
return IsGenericTypeParam(type, paramPosition);
case SignatureTypeCode.GenericMethodParameter:
paramPosition = signature[position++];
return IsGenericMethodTypeParam(type, paramPosition);
case SignatureTypeCode.GenericTypeInstance:
if (!MatchType(GetGenericTypeDefinition(type), signature, ref position))
{
return false;
}
int argumentCount = signature[position++];
for (int argumentIndex = 0; argumentIndex < argumentCount; argumentIndex++)
{
if (!MatchType(GetGenericTypeArgument(type, argumentIndex), signature, ref position))
{
return false;
}
}
return true;
default:
throw ExceptionUtilities.UnexpectedValue(typeCode);
}
}
/// <summary>
/// Read a type Id from the signature.
/// This may consume one or two bytes, and therefore increment the position correspondingly.
/// </summary>
private static short ReadTypeId(ImmutableArray<byte> signature, ref int position)
{
var firstByte = signature[position++];
if (firstByte == (byte)WellKnownType.ExtSentinel)
{
return (short)(signature[position++] + WellKnownType.ExtSentinel);
}
else
{
return firstByte;
}
}
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetGenericTypeArgument(TypeSymbol type, int argumentIndex);
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetGenericTypeDefinition(TypeSymbol type);
protected abstract bool IsGenericMethodTypeParam(TypeSymbol type, int paramPosition);
protected abstract bool IsGenericTypeParam(TypeSymbol type, int paramPosition);
/// <summary>
/// Should only accept Pointer types.
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetPointedToType(TypeSymbol type);
/// <summary>
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetSZArrayElementType(TypeSymbol type);
/// <summary>
/// Should only accept multi-dimensional arrays.
/// </summary>
protected abstract bool MatchArrayRank(TypeSymbol type, int countOfDimensions);
/// <summary>
/// Should only accept multi-dimensional arrays.
/// Should return null in case of error.
/// </summary>
protected abstract TypeSymbol? GetMDArrayElementType(TypeSymbol type);
protected abstract bool MatchTypeToTypeId(TypeSymbol type, int typeId);
protected abstract TypeSymbol GetReturnType(MethodSymbol method);
protected abstract ImmutableArray<ParameterSymbol> GetParameters(MethodSymbol method);
protected abstract TypeSymbol GetPropertyType(PropertySymbol property);
protected abstract ImmutableArray<ParameterSymbol> GetParameters(PropertySymbol property);
protected abstract TypeSymbol GetParamType(ParameterSymbol parameter);
protected abstract bool IsByRefParam(ParameterSymbol parameter);
protected abstract bool IsByRefMethod(MethodSymbol method);
protected abstract bool IsByRefProperty(PropertySymbol property);
protected abstract TypeSymbol GetFieldType(FieldSymbol field);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/Completion/CompletionProviders/FunctionPointerUnmanagedCallingConventionCompletionProviderTests.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.Tasks;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
[Trait(Traits.Feature, Traits.Features.Completion)]
public class FunctionPointerUnmanagedCallingConventionCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType() => typeof(FunctionPointerUnmanagedCallingConventionCompletionProvider);
[Fact]
public async Task TypeFound()
{
var markup = @"
namespace System.Runtime.CompilerServices
{
public class CallConvUnitTest { }
}
class C
{
delegate* unmanaged[$$] <int, string> f;
}";
await VerifyItemExistsAsync(markup, "UnitTest");
}
[Fact]
public async Task TypeFoundSecondCallingConvention()
{
var markup = @"
namespace System.Runtime.CompilerServices
{
public class CallConvUnitTest { }
}
class C
{
delegate* unmanaged[Thiscall, $$] <int, string> f;
}";
await VerifyItemExistsAsync(markup, "UnitTest");
}
[Theory]
[InlineData("Cdecl")]
[InlineData("Fastcall")]
[InlineData("Thiscall")]
[InlineData("Stdcall")]
public async Task PredefinedCallingConventionFound(string callingConvention)
{
// We explicitly create a project with no references (not even common references) to ensure we
// get the defaults
var markup = @"
<Workspace>
<Project Language=""C#"">
<Document>
class C
{
delegate* unmanaged[$$] <int, string> f;
}
</Document>
</Project>
</Workspace>";
await VerifyItemExistsAsync(markup, callingConvention, glyph: (int)Glyph.Keyword);
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more 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.Tasks;
using Microsoft.CodeAnalysis.CSharp.Completion.Providers;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Completion.CompletionProviders
{
[Trait(Traits.Feature, Traits.Features.Completion)]
public class FunctionPointerUnmanagedCallingConventionCompletionProviderTests : AbstractCSharpCompletionProviderTests
{
internal override Type GetCompletionProviderType() => typeof(FunctionPointerUnmanagedCallingConventionCompletionProvider);
[Fact]
public async Task TypeFound()
{
var markup = @"
namespace System.Runtime.CompilerServices
{
public class CallConvUnitTest { }
}
class C
{
delegate* unmanaged[$$] <int, string> f;
}";
await VerifyItemExistsAsync(markup, "UnitTest");
}
[Fact]
public async Task TypeFoundSecondCallingConvention()
{
var markup = @"
namespace System.Runtime.CompilerServices
{
public class CallConvUnitTest { }
}
class C
{
delegate* unmanaged[Thiscall, $$] <int, string> f;
}";
await VerifyItemExistsAsync(markup, "UnitTest");
}
[Theory]
[InlineData("Cdecl")]
[InlineData("Fastcall")]
[InlineData("Thiscall")]
[InlineData("Stdcall")]
public async Task PredefinedCallingConventionFound(string callingConvention)
{
// We explicitly create a project with no references (not even common references) to ensure we
// get the defaults
var markup = @"
<Workspace>
<Project Language=""C#"">
<Document>
class C
{
delegate* unmanaged[$$] <int, string> f;
}
</Document>
</Project>
</Workspace>";
await VerifyItemExistsAsync(markup, callingConvention, glyph: (int)Glyph.Keyword);
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Tools/AnalyzerRunner/AnalyzerRunnerMefHostServices.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.Host.Mef;
namespace AnalyzerRunner
{
internal static class AnalyzerRunnerMefHostServices
{
private static MefHostServices s_defaultServices;
public static MefHostServices DefaultServices
{
get
{
if (s_defaultServices is null)
{
Interlocked.CompareExchange(ref s_defaultServices, MefHostServices.Create(DefaultAssemblies), null);
}
return s_defaultServices;
}
}
private static ImmutableArray<Assembly> DefaultAssemblies
=> MSBuildMefHostServices.DefaultAssemblies.Add(typeof(AnalyzerRunnerMefHostServices).Assembly);
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Reflection;
using System.Threading;
using Microsoft.CodeAnalysis.Host.Mef;
namespace AnalyzerRunner
{
internal static class AnalyzerRunnerMefHostServices
{
private static MefHostServices s_defaultServices;
public static MefHostServices DefaultServices
{
get
{
if (s_defaultServices is null)
{
Interlocked.CompareExchange(ref s_defaultServices, MefHostServices.Create(DefaultAssemblies), null);
}
return s_defaultServices;
}
}
private static ImmutableArray<Assembly> DefaultAssemblies
=> MSBuildMefHostServices.DefaultAssemblies.Add(typeof(AnalyzerRunnerMefHostServices).Assembly);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/VisualStudio/CSharp/Impl/Options/AutomationObject/AutomationObject.ObsoleteAndUnused.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;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
/// <summary>
/// Unused. But kept around for back compat. Note this option is not about
/// turning warning into errors. It's about an aspect of 'remove unused using'
/// functionality we don't support anymore. Namely whether or not 'remove unused
/// using' should warn if you have any build errors as that might mean we
/// remove some usings inappropriately.
/// </summary>
public int WarnOnBuildErrors
{
get { return 0; }
set { }
}
public int ShowKeywords
{
get { return 0; }
set { }
}
[Obsolete("ClosedFileDiagnostics has been deprecated")]
public int ClosedFileDiagnostics
{
get { return 0; }
set { }
}
[Obsolete("CSharpClosedFileDiagnostics has been deprecated")]
public int CSharpClosedFileDiagnostics
{
get { return 0; }
set { }
}
[Obsolete("Use SnippetsBehavior instead")]
public int ShowSnippets
{
get
{
return GetOption(CompletionOptions.SnippetsBehavior) == SnippetsRule.AlwaysInclude
? 1 : 0;
}
set
{
if (value == 0)
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude);
}
else
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.AlwaysInclude);
}
}
}
[Obsolete("Use Style_UseImplicitTypeWherePossible, Style_UseImplicitTypeWhereApparent or Style_UseImplicitTypeForIntrinsicTypes", error: true)]
public int Style_UseVarWhenDeclaringLocals
{
get { return 0; }
set { }
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Completion;
namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options
{
public partial class AutomationObject
{
/// <summary>
/// Unused. But kept around for back compat. Note this option is not about
/// turning warning into errors. It's about an aspect of 'remove unused using'
/// functionality we don't support anymore. Namely whether or not 'remove unused
/// using' should warn if you have any build errors as that might mean we
/// remove some usings inappropriately.
/// </summary>
public int WarnOnBuildErrors
{
get { return 0; }
set { }
}
public int ShowKeywords
{
get { return 0; }
set { }
}
[Obsolete("ClosedFileDiagnostics has been deprecated")]
public int ClosedFileDiagnostics
{
get { return 0; }
set { }
}
[Obsolete("CSharpClosedFileDiagnostics has been deprecated")]
public int CSharpClosedFileDiagnostics
{
get { return 0; }
set { }
}
[Obsolete("Use SnippetsBehavior instead")]
public int ShowSnippets
{
get
{
return GetOption(CompletionOptions.SnippetsBehavior) == SnippetsRule.AlwaysInclude
? 1 : 0;
}
set
{
if (value == 0)
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.NeverInclude);
}
else
{
SetOption(CompletionOptions.SnippetsBehavior, SnippetsRule.AlwaysInclude);
}
}
}
[Obsolete("Use Style_UseImplicitTypeWherePossible, Style_UseImplicitTypeWhereApparent or Style_UseImplicitTypeForIntrinsicTypes", error: true)]
public int Style_UseVarWhenDeclaringLocals
{
get { return 0; }
set { }
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Compilers/CSharp/Test/Symbol/Symbols/TypeUnificationTests.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeUnificationTests : CSharpTestBase
{
[Fact]
public void TestNoTypeParameters()
{
var text =
@"
enum E
{
Element,
}
class C
{
//atomic
int i;
string s;
System.IFormattable f;
E e;
AnErrorType err;
void M() { }
//recursive
int[] a1;
int[][] a2;
int[,] a3;
int* p1;
int** p2;
System.Collections.Generic.Dictionary<int, long> g1;
System.Collections.Generic.Dictionary<long, int> g2;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var structType = @class.GetMember<FieldSymbol>("i").Type;
var classType = @class.GetMember<FieldSymbol>("s").Type;
var interfaceType = @class.GetMember<FieldSymbol>("f").Type;
var enumType = @class.GetMember<FieldSymbol>("e").Type;
var errorType = @class.GetMember<FieldSymbol>("err").Type;
var voidType = @class.GetMember<MethodSymbol>("M").ReturnType;
var arrayType1 = @class.GetMember<FieldSymbol>("a1").Type;
var arrayType2 = @class.GetMember<FieldSymbol>("a2").Type;
var arrayType3 = @class.GetMember<FieldSymbol>("a3").Type;
var pointerType1 = @class.GetMember<FieldSymbol>("p1").Type;
var pointerType2 = @class.GetMember<FieldSymbol>("p2").Type;
var genericType1 = @class.GetMember<FieldSymbol>("g1").Type;
var genericType2 = @class.GetMember<FieldSymbol>("g2").Type;
var types = new[]
{
structType,
classType,
interfaceType,
enumType,
errorType,
voidType,
arrayType1,
arrayType2,
arrayType3,
//UNDONE: pointerType1,
//UNDONE: pointerType2,
genericType1,
genericType2,
};
foreach (var t1 in types)
{
foreach (var t2 in types)
{
if (ReferenceEquals(t1, t2))
{
AssertCanUnify(t1, t2);
}
else
{
AssertCannotUnify(t1, t2);
}
}
}
AssertCanUnify(null, null);
AssertCannotUnify(classType, null);
}
[Fact]
public void TestJustTypeParameter()
{
var text =
@"
class C<T, U>
{
//atomic
int i;
string s;
System.IFormattable f;
AnErrorType e;
void M() { }
//recursive
int[] a1;
int[][] a2;
int[,] a3;
int* p1;
int** p2;
delegate*<void> fp1;
System.Collections.Generic.Dictionary<int, long> g1;
System.Collections.Generic.Dictionary<long, int> g2;
T tp1;
U tp2;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var structType = @class.GetMember<FieldSymbol>("i").Type;
var classType = @class.GetMember<FieldSymbol>("s").Type;
var interfaceType = @class.GetMember<FieldSymbol>("f").Type;
var errorType = @class.GetMember<FieldSymbol>("e").Type;
var voidType = @class.GetMember<MethodSymbol>("M").ReturnType;
var arrayType1 = @class.GetMember<FieldSymbol>("a1").Type;
var arrayType2 = @class.GetMember<FieldSymbol>("a2").Type;
var arrayType3 = @class.GetMember<FieldSymbol>("a3").Type;
var pointerType1 = @class.GetMember<FieldSymbol>("p1").Type;
var pointerType2 = @class.GetMember<FieldSymbol>("p2").Type;
var functionPointerType = @class.GetMember<FieldSymbol>("fp1").Type;
var genericType1 = @class.GetMember<FieldSymbol>("g1").Type;
var genericType2 = @class.GetMember<FieldSymbol>("g2").Type;
var typeParam1 = @class.GetMember<FieldSymbol>("tp1").Type;
var typeParam2 = @class.GetMember<FieldSymbol>("tp2").Type;
var substitutableTypes = new[]
{
structType,
classType,
interfaceType,
errorType,
arrayType1,
arrayType2,
arrayType3,
genericType1,
genericType2,
};
foreach (var t in substitutableTypes)
{
AssertCanUnify(typeParam1, t);
}
var unsubstitutableTypes = new[]
{
voidType,
pointerType1,
pointerType2,
functionPointerType,
};
foreach (var t in unsubstitutableTypes)
{
AssertCannotUnify(typeParam1, t);
}
AssertCanUnify(typeParam1, typeParam2);
}
[Fact]
public void TestArrayTypes()
{
var text =
@"
class C<T>
{
int[] a1;
int[][] a2;
int[,] a3;
T[] g1;
T[][] g2;
T[,] g3;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var arrayType1 = @class.GetMember<FieldSymbol>("a1").Type;
var arrayType2 = @class.GetMember<FieldSymbol>("a2").Type;
var arrayType3 = @class.GetMember<FieldSymbol>("a3").Type;
var genericType1 = @class.GetMember<FieldSymbol>("g1").Type;
var genericType2 = @class.GetMember<FieldSymbol>("g2").Type;
var genericType3 = @class.GetMember<FieldSymbol>("g3").Type;
AssertCanUnify(genericType1, arrayType1);
AssertCanUnify(genericType2, arrayType2);
AssertCanUnify(genericType3, arrayType3);
}
//UNDONE: public void TestPointerTypes()
[Fact]
public void TestNamedTypes()
{
var text =
@"
class C<W, X>
{
C<int, short> g1;
C<W, short> g2;
C<int, X> g3;
C<W, X> g4;
C<W, W> g5;
C<int, W> g6;
D<T> g7;
}
class D<T>
{
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var type1 = @class.GetMember<FieldSymbol>("g1").Type;
var type2 = @class.GetMember<FieldSymbol>("g2").Type;
var type3 = @class.GetMember<FieldSymbol>("g3").Type;
var type4 = @class.GetMember<FieldSymbol>("g4").Type;
var type5 = @class.GetMember<FieldSymbol>("g5").Type;
var type6 = @class.GetMember<FieldSymbol>("g6").Type;
var type7 = @class.GetMember<FieldSymbol>("g7").Type;
var types1To4 = new[] { type1, type2, type3, type4 };
foreach (var t1 in types1To4)
{
foreach (var t2 in types1To4)
{
AssertCanUnify(t1, t2);
}
}
AssertCannotUnify(type5, type1);
AssertCannotUnify(type6, type2);
AssertCannotUnify(type7, type3);
}
[Fact]
public void TestNestedNamedTypes()
{
var text =
@"
class C<X, Y>
{
L<int>.M<short> g1;
L<X>.M<short> g2;
L<int>.M<Y> g3;
L<X>.M<Y> g4;
L<X>.M<X> g5;
L<int>.M<X> g6;
}
public class L<T>
{
public class M<U>
{
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var type1 = @class.GetMember<FieldSymbol>("g1").Type;
var type2 = @class.GetMember<FieldSymbol>("g2").Type;
var type3 = @class.GetMember<FieldSymbol>("g3").Type;
var type4 = @class.GetMember<FieldSymbol>("g4").Type;
var type5 = @class.GetMember<FieldSymbol>("g5").Type;
var type6 = @class.GetMember<FieldSymbol>("g6").Type;
var types1To4 = new[] { type1, type2, type3, type4 };
foreach (var t1 in types1To4)
{
foreach (var t2 in types1To4)
{
AssertCanUnify(t1, t2);
}
}
AssertCannotUnify(type5, type1);
AssertCannotUnify(type6, type2);
}
[Fact]
public void TestOccursCheck()
{
var text =
@"
class C<T>
{
T contained;
C<T> containing;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var containedType = @class.GetMember<FieldSymbol>("contained").Type;
var containingType = @class.GetMember<FieldSymbol>("containing").Type;
AssertCannotUnify(containedType, containingType);
}
[Fact]
public void TestRecursiveCases()
{
var text =
@"
class C<W, X, Y, Z>
{
L<L<X[]>.M<Y>[]>.M<L<Y[,]>.M<X[]>[,]> t1;
L<L<int[]>.M<short>[]>.M<L<short[,]>.M<int[]>[,]> t2;
L<Y>.M<Z> t3;
L<W>.M<Z> t4;
L<W[]>.M<Z[,]> t5;
L<W[,]>.M<Z[]> t6;
}
public class L<T>
{
public class M<U>
{
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var type1 = @class.GetMember<FieldSymbol>("t1").Type;
var type2 = @class.GetMember<FieldSymbol>("t2").Type;
var type3 = @class.GetMember<FieldSymbol>("t3").Type;
var type4 = @class.GetMember<FieldSymbol>("t4").Type;
var type5 = @class.GetMember<FieldSymbol>("t5").Type;
var type6 = @class.GetMember<FieldSymbol>("t6").Type;
AssertCanUnify(type1, type1);
AssertCanUnify(type1, type2);
AssertCannotUnify(type1, type3);
AssertCanUnify(type1, type4);
AssertCanUnify(type1, type5);
AssertCannotUnify(type1, type6);
AssertCanUnify(type2, type2);
AssertCanUnify(type2, type3);
AssertCanUnify(type2, type4);
AssertCanUnify(type2, type5);
AssertCannotUnify(type2, type6);
AssertCanUnify(type3, type3);
AssertCanUnify(type3, type4);
AssertCannotUnify(type3, type5);
AssertCannotUnify(type3, type6);
AssertCanUnify(type4, type4);
AssertCannotUnify(type4, type5);
AssertCannotUnify(type4, type6);
AssertCanUnify(type5, type5);
AssertCannotUnify(type5, type6);
AssertCanUnify(type6, type6);
}
[WorkItem(1042692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042692")]
[Fact]
public void SubstituteWithOtherTypeParameter()
{
var text =
@"interface IA<T, U>
{
}
interface IB<T, U> : IA<U, object>, IA<T, U>
{
}";
var comp = CreateCompilation(text);
var type = comp.GetMember<NamedTypeSymbol>("IB");
AssertCanUnify(type.Interfaces()[0], type.Interfaces()[1]);
DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(),
new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 4, Column = 11 });
}
private static void AssertCanUnify(TypeSymbol t1, TypeSymbol t2)
{
Assert.True(TypeUnification.CanUnify(t1, t2), string.Format("{0} vs {1}", t1, t2));
Assert.True(TypeUnification.CanUnify(t2, t1), string.Format("{0} vs {1}", t2, t1));
}
private static void AssertCannotUnify(TypeSymbol t1, TypeSymbol t2)
{
Assert.False(TypeUnification.CanUnify(t1, t2), string.Format("{0} vs {1}", t1, t2));
Assert.False(TypeUnification.CanUnify(t2, t1), string.Format("{0} vs {1}", t2, t1));
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class TypeUnificationTests : CSharpTestBase
{
[Fact]
public void TestNoTypeParameters()
{
var text =
@"
enum E
{
Element,
}
class C
{
//atomic
int i;
string s;
System.IFormattable f;
E e;
AnErrorType err;
void M() { }
//recursive
int[] a1;
int[][] a2;
int[,] a3;
int* p1;
int** p2;
System.Collections.Generic.Dictionary<int, long> g1;
System.Collections.Generic.Dictionary<long, int> g2;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var structType = @class.GetMember<FieldSymbol>("i").Type;
var classType = @class.GetMember<FieldSymbol>("s").Type;
var interfaceType = @class.GetMember<FieldSymbol>("f").Type;
var enumType = @class.GetMember<FieldSymbol>("e").Type;
var errorType = @class.GetMember<FieldSymbol>("err").Type;
var voidType = @class.GetMember<MethodSymbol>("M").ReturnType;
var arrayType1 = @class.GetMember<FieldSymbol>("a1").Type;
var arrayType2 = @class.GetMember<FieldSymbol>("a2").Type;
var arrayType3 = @class.GetMember<FieldSymbol>("a3").Type;
var pointerType1 = @class.GetMember<FieldSymbol>("p1").Type;
var pointerType2 = @class.GetMember<FieldSymbol>("p2").Type;
var genericType1 = @class.GetMember<FieldSymbol>("g1").Type;
var genericType2 = @class.GetMember<FieldSymbol>("g2").Type;
var types = new[]
{
structType,
classType,
interfaceType,
enumType,
errorType,
voidType,
arrayType1,
arrayType2,
arrayType3,
//UNDONE: pointerType1,
//UNDONE: pointerType2,
genericType1,
genericType2,
};
foreach (var t1 in types)
{
foreach (var t2 in types)
{
if (ReferenceEquals(t1, t2))
{
AssertCanUnify(t1, t2);
}
else
{
AssertCannotUnify(t1, t2);
}
}
}
AssertCanUnify(null, null);
AssertCannotUnify(classType, null);
}
[Fact]
public void TestJustTypeParameter()
{
var text =
@"
class C<T, U>
{
//atomic
int i;
string s;
System.IFormattable f;
AnErrorType e;
void M() { }
//recursive
int[] a1;
int[][] a2;
int[,] a3;
int* p1;
int** p2;
delegate*<void> fp1;
System.Collections.Generic.Dictionary<int, long> g1;
System.Collections.Generic.Dictionary<long, int> g2;
T tp1;
U tp2;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var structType = @class.GetMember<FieldSymbol>("i").Type;
var classType = @class.GetMember<FieldSymbol>("s").Type;
var interfaceType = @class.GetMember<FieldSymbol>("f").Type;
var errorType = @class.GetMember<FieldSymbol>("e").Type;
var voidType = @class.GetMember<MethodSymbol>("M").ReturnType;
var arrayType1 = @class.GetMember<FieldSymbol>("a1").Type;
var arrayType2 = @class.GetMember<FieldSymbol>("a2").Type;
var arrayType3 = @class.GetMember<FieldSymbol>("a3").Type;
var pointerType1 = @class.GetMember<FieldSymbol>("p1").Type;
var pointerType2 = @class.GetMember<FieldSymbol>("p2").Type;
var functionPointerType = @class.GetMember<FieldSymbol>("fp1").Type;
var genericType1 = @class.GetMember<FieldSymbol>("g1").Type;
var genericType2 = @class.GetMember<FieldSymbol>("g2").Type;
var typeParam1 = @class.GetMember<FieldSymbol>("tp1").Type;
var typeParam2 = @class.GetMember<FieldSymbol>("tp2").Type;
var substitutableTypes = new[]
{
structType,
classType,
interfaceType,
errorType,
arrayType1,
arrayType2,
arrayType3,
genericType1,
genericType2,
};
foreach (var t in substitutableTypes)
{
AssertCanUnify(typeParam1, t);
}
var unsubstitutableTypes = new[]
{
voidType,
pointerType1,
pointerType2,
functionPointerType,
};
foreach (var t in unsubstitutableTypes)
{
AssertCannotUnify(typeParam1, t);
}
AssertCanUnify(typeParam1, typeParam2);
}
[Fact]
public void TestArrayTypes()
{
var text =
@"
class C<T>
{
int[] a1;
int[][] a2;
int[,] a3;
T[] g1;
T[][] g2;
T[,] g3;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var arrayType1 = @class.GetMember<FieldSymbol>("a1").Type;
var arrayType2 = @class.GetMember<FieldSymbol>("a2").Type;
var arrayType3 = @class.GetMember<FieldSymbol>("a3").Type;
var genericType1 = @class.GetMember<FieldSymbol>("g1").Type;
var genericType2 = @class.GetMember<FieldSymbol>("g2").Type;
var genericType3 = @class.GetMember<FieldSymbol>("g3").Type;
AssertCanUnify(genericType1, arrayType1);
AssertCanUnify(genericType2, arrayType2);
AssertCanUnify(genericType3, arrayType3);
}
//UNDONE: public void TestPointerTypes()
[Fact]
public void TestNamedTypes()
{
var text =
@"
class C<W, X>
{
C<int, short> g1;
C<W, short> g2;
C<int, X> g3;
C<W, X> g4;
C<W, W> g5;
C<int, W> g6;
D<T> g7;
}
class D<T>
{
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var type1 = @class.GetMember<FieldSymbol>("g1").Type;
var type2 = @class.GetMember<FieldSymbol>("g2").Type;
var type3 = @class.GetMember<FieldSymbol>("g3").Type;
var type4 = @class.GetMember<FieldSymbol>("g4").Type;
var type5 = @class.GetMember<FieldSymbol>("g5").Type;
var type6 = @class.GetMember<FieldSymbol>("g6").Type;
var type7 = @class.GetMember<FieldSymbol>("g7").Type;
var types1To4 = new[] { type1, type2, type3, type4 };
foreach (var t1 in types1To4)
{
foreach (var t2 in types1To4)
{
AssertCanUnify(t1, t2);
}
}
AssertCannotUnify(type5, type1);
AssertCannotUnify(type6, type2);
AssertCannotUnify(type7, type3);
}
[Fact]
public void TestNestedNamedTypes()
{
var text =
@"
class C<X, Y>
{
L<int>.M<short> g1;
L<X>.M<short> g2;
L<int>.M<Y> g3;
L<X>.M<Y> g4;
L<X>.M<X> g5;
L<int>.M<X> g6;
}
public class L<T>
{
public class M<U>
{
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var type1 = @class.GetMember<FieldSymbol>("g1").Type;
var type2 = @class.GetMember<FieldSymbol>("g2").Type;
var type3 = @class.GetMember<FieldSymbol>("g3").Type;
var type4 = @class.GetMember<FieldSymbol>("g4").Type;
var type5 = @class.GetMember<FieldSymbol>("g5").Type;
var type6 = @class.GetMember<FieldSymbol>("g6").Type;
var types1To4 = new[] { type1, type2, type3, type4 };
foreach (var t1 in types1To4)
{
foreach (var t2 in types1To4)
{
AssertCanUnify(t1, t2);
}
}
AssertCannotUnify(type5, type1);
AssertCannotUnify(type6, type2);
}
[Fact]
public void TestOccursCheck()
{
var text =
@"
class C<T>
{
T contained;
C<T> containing;
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var containedType = @class.GetMember<FieldSymbol>("contained").Type;
var containingType = @class.GetMember<FieldSymbol>("containing").Type;
AssertCannotUnify(containedType, containingType);
}
[Fact]
public void TestRecursiveCases()
{
var text =
@"
class C<W, X, Y, Z>
{
L<L<X[]>.M<Y>[]>.M<L<Y[,]>.M<X[]>[,]> t1;
L<L<int[]>.M<short>[]>.M<L<short[,]>.M<int[]>[,]> t2;
L<Y>.M<Z> t3;
L<W>.M<Z> t4;
L<W[]>.M<Z[,]> t5;
L<W[,]>.M<Z[]> t6;
}
public class L<T>
{
public class M<U>
{
}
}
";
var comp = CreateCompilation(text);
var global = comp.GlobalNamespace;
var @class = global.GetMember<NamedTypeSymbol>("C");
var type1 = @class.GetMember<FieldSymbol>("t1").Type;
var type2 = @class.GetMember<FieldSymbol>("t2").Type;
var type3 = @class.GetMember<FieldSymbol>("t3").Type;
var type4 = @class.GetMember<FieldSymbol>("t4").Type;
var type5 = @class.GetMember<FieldSymbol>("t5").Type;
var type6 = @class.GetMember<FieldSymbol>("t6").Type;
AssertCanUnify(type1, type1);
AssertCanUnify(type1, type2);
AssertCannotUnify(type1, type3);
AssertCanUnify(type1, type4);
AssertCanUnify(type1, type5);
AssertCannotUnify(type1, type6);
AssertCanUnify(type2, type2);
AssertCanUnify(type2, type3);
AssertCanUnify(type2, type4);
AssertCanUnify(type2, type5);
AssertCannotUnify(type2, type6);
AssertCanUnify(type3, type3);
AssertCanUnify(type3, type4);
AssertCannotUnify(type3, type5);
AssertCannotUnify(type3, type6);
AssertCanUnify(type4, type4);
AssertCannotUnify(type4, type5);
AssertCannotUnify(type4, type6);
AssertCanUnify(type5, type5);
AssertCannotUnify(type5, type6);
AssertCanUnify(type6, type6);
}
[WorkItem(1042692, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1042692")]
[Fact]
public void SubstituteWithOtherTypeParameter()
{
var text =
@"interface IA<T, U>
{
}
interface IB<T, U> : IA<U, object>, IA<T, U>
{
}";
var comp = CreateCompilation(text);
var type = comp.GetMember<NamedTypeSymbol>("IB");
AssertCanUnify(type.Interfaces()[0], type.Interfaces()[1]);
DiagnosticsUtils.VerifyErrorCodes(comp.GetDiagnostics(),
new ErrorDescription { Code = (int)ErrorCode.ERR_UnifyingInterfaceInstantiations, Line = 4, Column = 11 });
}
private static void AssertCanUnify(TypeSymbol t1, TypeSymbol t2)
{
Assert.True(TypeUnification.CanUnify(t1, t2), string.Format("{0} vs {1}", t1, t2));
Assert.True(TypeUnification.CanUnify(t2, t1), string.Format("{0} vs {1}", t2, t1));
}
private static void AssertCannotUnify(TypeSymbol t1, TypeSymbol t2)
{
Assert.False(TypeUnification.CanUnify(t1, t2), string.Format("{0} vs {1}", t1, t2));
Assert.False(TypeUnification.CanUnify(t2, t1), string.Format("{0} vs {1}", t2, t1));
}
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/Workspaces/Core/Portable/Differencing/AbstractSyntaxComparer.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Differencing
{
internal abstract class AbstractSyntaxComparer : TreeComparer<SyntaxNode>
{
protected const double ExactMatchDist = 0.0;
protected const double EpsilonDist = 0.00001;
internal const int IgnoredNode = -1;
protected readonly SyntaxNode? _oldRoot;
protected readonly SyntaxNode? _newRoot;
private readonly IEnumerable<SyntaxNode>? _oldRootChildren;
private readonly IEnumerable<SyntaxNode>? _newRootChildren;
// This comparer can operate in two modes:
// * Top level syntax, which looks at member declarations, but doesn't look inside method bodies etc.
// * Statement syntax, which looks into member bodies and descends through all statements and expressions
// This flag is used where there needs to be a distinction made between how these are treated
protected readonly bool _compareStatementSyntax;
internal AbstractSyntaxComparer(
SyntaxNode? oldRoot,
SyntaxNode? newRoot,
IEnumerable<SyntaxNode>? oldRootChildren,
IEnumerable<SyntaxNode>? newRootChildren,
bool compareStatementSyntax)
{
_compareStatementSyntax = compareStatementSyntax;
_oldRoot = oldRoot;
_newRoot = newRoot;
_oldRootChildren = oldRootChildren;
_newRootChildren = newRootChildren;
}
protected internal sealed override bool TreesEqual(SyntaxNode oldNode, SyntaxNode newNode)
=> oldNode.SyntaxTree == newNode.SyntaxTree;
protected internal sealed override TextSpan GetSpan(SyntaxNode node)
=> node.Span;
/// <summary>
/// Calculates distance of two nodes based on their significant parts.
/// Returns false if the nodes don't have any significant parts and should be compared as a whole.
/// </summary>
protected abstract bool TryComputeWeightedDistance(SyntaxNode oldNode, SyntaxNode newNode, out double distance);
protected abstract bool IsLambdaBodyStatementOrExpression(SyntaxNode node);
protected internal override bool TryGetParent(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? parent)
{
if (node == _oldRoot || node == _newRoot)
{
parent = null;
return false;
}
parent = node.Parent;
while (parent != null && !HasLabel(parent))
{
parent = parent.Parent;
}
return parent != null;
}
protected internal override IEnumerable<SyntaxNode>? GetChildren(SyntaxNode node)
{
if (node == _oldRoot)
{
return _oldRootChildren;
}
if (node == _newRoot)
{
return _newRootChildren;
}
return HasChildren(node) ? EnumerateChildren(node) : null;
}
private IEnumerable<SyntaxNode> EnumerateChildren(SyntaxNode node)
{
foreach (var child in node.ChildNodes())
{
if (IsLambdaBodyStatementOrExpression(child))
{
continue;
}
if (HasLabel(child))
{
yield return child;
}
else if (_compareStatementSyntax)
{
foreach (var descendant in child.DescendantNodes(DescendIntoChildren))
{
if (HasLabel(descendant))
{
yield return descendant;
}
}
}
}
}
private bool DescendIntoChildren(SyntaxNode node)
=> !IsLambdaBodyStatementOrExpression(node) && !HasLabel(node);
protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node)
{
var rootChildren = (node == _oldRoot) ? _oldRootChildren : (node == _newRoot) ? _newRootChildren : null;
return (rootChildren != null) ? EnumerateDescendants(rootChildren) : EnumerateDescendants(node);
}
private IEnumerable<SyntaxNode> EnumerateDescendants(IEnumerable<SyntaxNode> nodes)
{
foreach (var node in nodes)
{
if (HasLabel(node))
{
yield return node;
}
foreach (var descendant in EnumerateDescendants(node))
{
if (HasLabel(descendant))
{
yield return descendant;
}
}
}
}
private IEnumerable<SyntaxNode> EnumerateDescendants(SyntaxNode node)
{
foreach (var descendant in node.DescendantNodesAndTokens(
descendIntoChildren: child => ShouldEnumerateChildren(child),
descendIntoTrivia: false))
{
var descendantNode = descendant.AsNode();
if (descendantNode != null && HasLabel(descendantNode))
{
if (!IsLambdaBodyStatementOrExpression(descendantNode))
{
yield return descendantNode;
}
}
}
bool ShouldEnumerateChildren(SyntaxNode child)
{
// if we don't want to consider this nodes children, then don't
if (!HasChildren(child))
{
return false;
}
// Always descend into the children of the node we were asked about
if (child == node)
{
return true;
}
// otherwise, as long as we don't descend into lambdas
return !IsLambdaBodyStatementOrExpression(child);
}
}
protected bool HasChildren(SyntaxNode node)
{
// Leaves are labeled statements that don't have a labeled child.
// We also return true for non-labeled statements.
var label = Classify(node.RawKind, node, out var isLeaf);
// ignored should always be reported as leaves for top syntax, but for statements
// we want to look at all child nodes, because almost anything could have a lambda
if (!_compareStatementSyntax)
{
Debug.Assert(label != IgnoredNode || isLeaf);
}
return !isLeaf;
}
internal bool HasLabel(SyntaxNode node)
=> Classify(node.RawKind, node, out _) != IgnoredNode;
internal abstract int Classify(int kind, SyntaxNode? node, out bool isLeaf);
protected internal override int GetLabel(SyntaxNode node)
=> Classify(node.RawKind, node, 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 System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.Differencing
{
internal abstract class AbstractSyntaxComparer : TreeComparer<SyntaxNode>
{
protected const double ExactMatchDist = 0.0;
protected const double EpsilonDist = 0.00001;
internal const int IgnoredNode = -1;
protected readonly SyntaxNode? _oldRoot;
protected readonly SyntaxNode? _newRoot;
private readonly IEnumerable<SyntaxNode>? _oldRootChildren;
private readonly IEnumerable<SyntaxNode>? _newRootChildren;
// This comparer can operate in two modes:
// * Top level syntax, which looks at member declarations, but doesn't look inside method bodies etc.
// * Statement syntax, which looks into member bodies and descends through all statements and expressions
// This flag is used where there needs to be a distinction made between how these are treated
protected readonly bool _compareStatementSyntax;
internal AbstractSyntaxComparer(
SyntaxNode? oldRoot,
SyntaxNode? newRoot,
IEnumerable<SyntaxNode>? oldRootChildren,
IEnumerable<SyntaxNode>? newRootChildren,
bool compareStatementSyntax)
{
_compareStatementSyntax = compareStatementSyntax;
_oldRoot = oldRoot;
_newRoot = newRoot;
_oldRootChildren = oldRootChildren;
_newRootChildren = newRootChildren;
}
protected internal sealed override bool TreesEqual(SyntaxNode oldNode, SyntaxNode newNode)
=> oldNode.SyntaxTree == newNode.SyntaxTree;
protected internal sealed override TextSpan GetSpan(SyntaxNode node)
=> node.Span;
/// <summary>
/// Calculates distance of two nodes based on their significant parts.
/// Returns false if the nodes don't have any significant parts and should be compared as a whole.
/// </summary>
protected abstract bool TryComputeWeightedDistance(SyntaxNode oldNode, SyntaxNode newNode, out double distance);
protected abstract bool IsLambdaBodyStatementOrExpression(SyntaxNode node);
protected internal override bool TryGetParent(SyntaxNode node, [NotNullWhen(true)] out SyntaxNode? parent)
{
if (node == _oldRoot || node == _newRoot)
{
parent = null;
return false;
}
parent = node.Parent;
while (parent != null && !HasLabel(parent))
{
parent = parent.Parent;
}
return parent != null;
}
protected internal override IEnumerable<SyntaxNode>? GetChildren(SyntaxNode node)
{
if (node == _oldRoot)
{
return _oldRootChildren;
}
if (node == _newRoot)
{
return _newRootChildren;
}
return HasChildren(node) ? EnumerateChildren(node) : null;
}
private IEnumerable<SyntaxNode> EnumerateChildren(SyntaxNode node)
{
foreach (var child in node.ChildNodes())
{
if (IsLambdaBodyStatementOrExpression(child))
{
continue;
}
if (HasLabel(child))
{
yield return child;
}
else if (_compareStatementSyntax)
{
foreach (var descendant in child.DescendantNodes(DescendIntoChildren))
{
if (HasLabel(descendant))
{
yield return descendant;
}
}
}
}
}
private bool DescendIntoChildren(SyntaxNode node)
=> !IsLambdaBodyStatementOrExpression(node) && !HasLabel(node);
protected internal sealed override IEnumerable<SyntaxNode> GetDescendants(SyntaxNode node)
{
var rootChildren = (node == _oldRoot) ? _oldRootChildren : (node == _newRoot) ? _newRootChildren : null;
return (rootChildren != null) ? EnumerateDescendants(rootChildren) : EnumerateDescendants(node);
}
private IEnumerable<SyntaxNode> EnumerateDescendants(IEnumerable<SyntaxNode> nodes)
{
foreach (var node in nodes)
{
if (HasLabel(node))
{
yield return node;
}
foreach (var descendant in EnumerateDescendants(node))
{
if (HasLabel(descendant))
{
yield return descendant;
}
}
}
}
private IEnumerable<SyntaxNode> EnumerateDescendants(SyntaxNode node)
{
foreach (var descendant in node.DescendantNodesAndTokens(
descendIntoChildren: child => ShouldEnumerateChildren(child),
descendIntoTrivia: false))
{
var descendantNode = descendant.AsNode();
if (descendantNode != null && HasLabel(descendantNode))
{
if (!IsLambdaBodyStatementOrExpression(descendantNode))
{
yield return descendantNode;
}
}
}
bool ShouldEnumerateChildren(SyntaxNode child)
{
// if we don't want to consider this nodes children, then don't
if (!HasChildren(child))
{
return false;
}
// Always descend into the children of the node we were asked about
if (child == node)
{
return true;
}
// otherwise, as long as we don't descend into lambdas
return !IsLambdaBodyStatementOrExpression(child);
}
}
protected bool HasChildren(SyntaxNode node)
{
// Leaves are labeled statements that don't have a labeled child.
// We also return true for non-labeled statements.
var label = Classify(node.RawKind, node, out var isLeaf);
// ignored should always be reported as leaves for top syntax, but for statements
// we want to look at all child nodes, because almost anything could have a lambda
if (!_compareStatementSyntax)
{
Debug.Assert(label != IgnoredNode || isLeaf);
}
return !isLeaf;
}
internal bool HasLabel(SyntaxNode node)
=> Classify(node.RawKind, node, out _) != IgnoredNode;
internal abstract int Classify(int kind, SyntaxNode? node, out bool isLeaf);
protected internal override int GetLabel(SyntaxNode node)
=> Classify(node.RawKind, node, out _);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/UsingStatementHighlighter.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 UsingStatementHighlighter : AbstractKeywordHighlighter<UsingStatementSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UsingStatementHighlighter()
{
}
protected override void AddHighlights(UsingStatementSyntax usingStatement, List<TextSpan> highlights, CancellationToken cancellationToken)
=> highlights.Add(usingStatement.UsingKeyword.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 UsingStatementHighlighter : AbstractKeywordHighlighter<UsingStatementSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public UsingStatementHighlighter()
{
}
protected override void AddHighlights(UsingStatementSyntax usingStatement, List<TextSpan> highlights, CancellationToken cancellationToken)
=> highlights.Add(usingStatement.UsingKeyword.Span);
}
}
| -1 |
dotnet/roslyn | 54,991 | Fix 'group usings' with file scoped namespaces | Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | CyrusNajmabadi | 2021-07-20T20:49:49Z | 2021-07-20T23:09:58Z | 104a98c1f5800f35389dcdee43bb8b0f30f512e7 | 56ff80826007fb803fd46e7d6e7c319c738f55f0 | Fix 'group usings' with file scoped namespaces. Relates to test plan: https://github.com/dotnet/roslyn/issues/49000 | ./src/EditorFeatures/CSharpTest/ExtractMethod/ExtractMethodBase.cs | ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.ExtractMethod;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod
{
[UseExportProvider]
public class ExtractMethodBase
{
protected static async Task ExpectExtractMethodToFailAsync(string codeWithMarker, bool dontPutOutOrRefOnStruct = true, string[] features = null)
{
ParseOptions parseOptions = null;
if (features != null)
{
var featuresMapped = features.Select(x => new KeyValuePair<string, string>(x, string.Empty));
parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped);
}
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.First();
var textSpan = testDocument.SelectedSpans.Single();
var treeAfterExtractMethod = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct);
}
protected static async Task ExpectExtractMethodToFailAsync(
string codeWithMarker,
string expected,
bool dontPutOutOrRefOnStruct = true,
CSharpParseOptions parseOptions = null)
{
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.Single();
var subjectBuffer = testDocument.GetTextBuffer();
var tree = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct);
using (var edit = subjectBuffer.CreateEdit())
{
edit.Replace(0, edit.Snapshot.Length, tree.ToFullString());
edit.Apply();
}
if (expected == "")
Assert.True(false, subjectBuffer.CurrentSnapshot.GetText());
Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText());
}
protected static async Task NotSupported_ExtractMethodAsync(string codeWithMarker)
{
using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker))
{
Assert.NotNull(await Record.ExceptionAsync(async () =>
{
var testDocument = workspace.Documents.Single();
var tree = await ExtractMethodAsync(workspace, testDocument);
}));
}
}
protected static async Task TestExtractMethodAsync(
string codeWithMarker,
string expected,
bool temporaryFailing = false,
bool dontPutOutOrRefOnStruct = true,
bool allowBestEffort = false,
CSharpParseOptions parseOptions = null)
{
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.Single();
var subjectBuffer = testDocument.GetTextBuffer();
var tree = await ExtractMethodAsync(
workspace, testDocument,
dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct,
allowBestEffort: allowBestEffort);
using (var edit = subjectBuffer.CreateEdit())
{
edit.Replace(0, edit.Snapshot.Length, tree.ToFullString());
edit.Apply();
}
var actual = subjectBuffer.CurrentSnapshot.GetText();
if (temporaryFailing)
{
Assert.NotEqual(expected, actual);
}
else
{
if (expected != "")
{
AssertEx.EqualOrDiff(expected, actual);
}
else
{
// print out the entire diff to make adding tests simpler.
Assert.Equal((object)expected, actual);
}
}
}
protected static async Task<SyntaxNode> ExtractMethodAsync(
TestWorkspace workspace,
TestHostDocument testDocument,
bool succeed = true,
bool dontPutOutOrRefOnStruct = true,
bool allowBestEffort = false)
{
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
Assert.NotNull(document);
var originalOptions = await document.GetOptionsAsync();
var options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct);
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options);
var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None);
if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion())
{
return null;
}
Assert.True(selectedCode.ContainsValidContext);
// extract method
var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, localFunction: false);
var result = await extractor.ExtractMethodAsync(CancellationToken.None);
Assert.NotNull(result);
Assert.Equal(succeed,
result.Succeeded ||
result.SucceededWithSuggestion ||
(allowBestEffort && result.Status.HasBestEffort()));
var doc = result.Document;
return doc == null
? null
: await doc.GetSyntaxRootAsync();
}
protected static async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null, TextSpan? textSpanOverride = null)
{
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.Single();
var namedSpans = testDocument.AnnotatedSpans;
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
Assert.NotNull(document);
var options = await document.GetOptionsAsync(CancellationToken.None);
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var validator = new CSharpSelectionValidator(semanticDocument, textSpanOverride ?? namedSpans["b"].Single(), options);
var result = await validator.GetValidSelectionAsync(CancellationToken.None);
Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded());
if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion())
{
Assert.Equal(namedSpans["r"].Single(), result.FinalSpan);
}
}
protected static async Task IterateAllAsync(string code)
{
using var workspace = TestWorkspace.CreateCSharp(code, CodeAnalysis.CSharp.Test.Utilities.TestOptions.Regular);
var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
Assert.NotNull(document);
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var root = await document.GetSyntaxRootAsync();
var iterator = root.DescendantNodesAndSelf().Cast<SyntaxNode>();
var originalOptions = await document.GetOptionsAsync();
foreach (var node in iterator)
{
var validator = new CSharpSelectionValidator(semanticDocument, node.Span, originalOptions);
var result = await validator.GetValidSelectionAsync(CancellationToken.None);
// check the obvious case
if (!(node is ExpressionSyntax) && !node.UnderValidContext())
{
Assert.True(result.Status.FailedWithNoBestEffortSuggestion());
}
}
}
}
}
| ๏ปฟ// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.ExtractMethod;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ExtractMethod
{
[UseExportProvider]
public class ExtractMethodBase
{
protected static async Task ExpectExtractMethodToFailAsync(string codeWithMarker, bool dontPutOutOrRefOnStruct = true, string[] features = null)
{
ParseOptions parseOptions = null;
if (features != null)
{
var featuresMapped = features.Select(x => new KeyValuePair<string, string>(x, string.Empty));
parseOptions = new CSharpParseOptions().WithFeatures(featuresMapped);
}
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.First();
var textSpan = testDocument.SelectedSpans.Single();
var treeAfterExtractMethod = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct);
}
protected static async Task ExpectExtractMethodToFailAsync(
string codeWithMarker,
string expected,
bool dontPutOutOrRefOnStruct = true,
CSharpParseOptions parseOptions = null)
{
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.Single();
var subjectBuffer = testDocument.GetTextBuffer();
var tree = await ExtractMethodAsync(workspace, testDocument, succeed: false, dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct);
using (var edit = subjectBuffer.CreateEdit())
{
edit.Replace(0, edit.Snapshot.Length, tree.ToFullString());
edit.Apply();
}
if (expected == "")
Assert.True(false, subjectBuffer.CurrentSnapshot.GetText());
Assert.Equal(expected, subjectBuffer.CurrentSnapshot.GetText());
}
protected static async Task NotSupported_ExtractMethodAsync(string codeWithMarker)
{
using (var workspace = TestWorkspace.CreateCSharp(codeWithMarker))
{
Assert.NotNull(await Record.ExceptionAsync(async () =>
{
var testDocument = workspace.Documents.Single();
var tree = await ExtractMethodAsync(workspace, testDocument);
}));
}
}
protected static async Task TestExtractMethodAsync(
string codeWithMarker,
string expected,
bool temporaryFailing = false,
bool dontPutOutOrRefOnStruct = true,
bool allowBestEffort = false,
CSharpParseOptions parseOptions = null)
{
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.Single();
var subjectBuffer = testDocument.GetTextBuffer();
var tree = await ExtractMethodAsync(
workspace, testDocument,
dontPutOutOrRefOnStruct: dontPutOutOrRefOnStruct,
allowBestEffort: allowBestEffort);
using (var edit = subjectBuffer.CreateEdit())
{
edit.Replace(0, edit.Snapshot.Length, tree.ToFullString());
edit.Apply();
}
var actual = subjectBuffer.CurrentSnapshot.GetText();
if (temporaryFailing)
{
Assert.NotEqual(expected, actual);
}
else
{
if (expected != "")
{
AssertEx.EqualOrDiff(expected, actual);
}
else
{
// print out the entire diff to make adding tests simpler.
Assert.Equal((object)expected, actual);
}
}
}
protected static async Task<SyntaxNode> ExtractMethodAsync(
TestWorkspace workspace,
TestHostDocument testDocument,
bool succeed = true,
bool dontPutOutOrRefOnStruct = true,
bool allowBestEffort = false)
{
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
Assert.NotNull(document);
var originalOptions = await document.GetOptionsAsync();
var options = originalOptions.WithChangedOption(ExtractMethodOptions.DontPutOutOrRefOnStruct, document.Project.Language, dontPutOutOrRefOnStruct);
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var validator = new CSharpSelectionValidator(semanticDocument, testDocument.SelectedSpans.Single(), options);
var selectedCode = await validator.GetValidSelectionAsync(CancellationToken.None);
if (!succeed && selectedCode.Status.FailedWithNoBestEffortSuggestion())
{
return null;
}
Assert.True(selectedCode.ContainsValidContext);
// extract method
var extractor = new CSharpMethodExtractor((CSharpSelectionResult)selectedCode, localFunction: false);
var result = await extractor.ExtractMethodAsync(CancellationToken.None);
Assert.NotNull(result);
Assert.Equal(succeed,
result.Succeeded ||
result.SucceededWithSuggestion ||
(allowBestEffort && result.Status.HasBestEffort()));
var doc = result.Document;
return doc == null
? null
: await doc.GetSyntaxRootAsync();
}
protected static async Task TestSelectionAsync(string codeWithMarker, bool expectedFail = false, CSharpParseOptions parseOptions = null, TextSpan? textSpanOverride = null)
{
using var workspace = TestWorkspace.CreateCSharp(codeWithMarker, parseOptions: parseOptions);
var testDocument = workspace.Documents.Single();
var namedSpans = testDocument.AnnotatedSpans;
var document = workspace.CurrentSolution.GetDocument(testDocument.Id);
Assert.NotNull(document);
var options = await document.GetOptionsAsync(CancellationToken.None);
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var validator = new CSharpSelectionValidator(semanticDocument, textSpanOverride ?? namedSpans["b"].Single(), options);
var result = await validator.GetValidSelectionAsync(CancellationToken.None);
Assert.True(expectedFail ? result.Status.Failed() : result.Status.Succeeded());
if ((result.Status.Succeeded() || result.Status.Flag.HasBestEffort()) && result.Status.Flag.HasSuggestion())
{
Assert.Equal(namedSpans["r"].Single(), result.FinalSpan);
}
}
protected static async Task IterateAllAsync(string code)
{
using var workspace = TestWorkspace.CreateCSharp(code, CodeAnalysis.CSharp.Test.Utilities.TestOptions.Regular);
var document = workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
Assert.NotNull(document);
var semanticDocument = await SemanticDocument.CreateAsync(document, CancellationToken.None);
var root = await document.GetSyntaxRootAsync();
var iterator = root.DescendantNodesAndSelf().Cast<SyntaxNode>();
var originalOptions = await document.GetOptionsAsync();
foreach (var node in iterator)
{
var validator = new CSharpSelectionValidator(semanticDocument, node.Span, originalOptions);
var result = await validator.GetValidSelectionAsync(CancellationToken.None);
// check the obvious case
if (!(node is ExpressionSyntax) && !node.UnderValidContext())
{
Assert.True(result.Status.FailedWithNoBestEffortSuggestion());
}
}
}
}
}
| -1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.