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,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Features/Core/Portable/LanguageServices/AnonymousTypeDisplayService/IAnonymousTypeDisplayExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal static class IAnonymousTypeDisplayExtensions
{
public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes(
this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position)
{
var result = parts;
while (true)
{
var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType());
if (delegateAnonymousType == null)
{
break;
}
result = result == parts ? new List<SymbolDisplayPart>(parts) : result;
ReplaceAnonymousType(result, delegateAnonymousType,
service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position));
}
return result;
}
private static void ReplaceAnonymousType(
IList<SymbolDisplayPart> list,
INamedTypeSymbol anonymousType,
IEnumerable<SymbolDisplayPart> parts)
{
var index = list.IndexOf(p => anonymousType.Equals(p.Symbol));
if (index >= 0)
{
var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList();
list.Clear();
list.AddRange(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.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.LanguageServices
{
internal static class IAnonymousTypeDisplayExtensions
{
public static IList<SymbolDisplayPart> InlineDelegateAnonymousTypes(
this IAnonymousTypeDisplayService service, IList<SymbolDisplayPart> parts, SemanticModel semanticModel, int position)
{
var result = parts;
while (true)
{
var delegateAnonymousType = result.Select(p => p.Symbol).OfType<INamedTypeSymbol>().FirstOrDefault(s => s.IsAnonymousDelegateType());
if (delegateAnonymousType == null)
{
break;
}
result = result == parts ? new List<SymbolDisplayPart>(parts) : result;
ReplaceAnonymousType(result, delegateAnonymousType,
service.GetAnonymousTypeParts(delegateAnonymousType, semanticModel, position));
}
return result;
}
private static void ReplaceAnonymousType(
IList<SymbolDisplayPart> list,
INamedTypeSymbol anonymousType,
IEnumerable<SymbolDisplayPart> parts)
{
var index = list.IndexOf(p => anonymousType.Equals(p.Symbol));
if (index >= 0)
{
var result = list.Take(index).Concat(parts).Concat(list.Skip(index + 1)).ToList();
list.Clear();
list.AddRange(result);
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Features/VisualBasic/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.MemberGroup.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.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Partial Friend Class InvocationExpressionSignatureHelpProvider
Private Shared Function GetAccessibleMembers(invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel,
within As ISymbol,
memberGroup As IEnumerable(Of ISymbol),
cancellationToken As CancellationToken) As ImmutableArray(Of ISymbol)
Dim throughType As ITypeSymbol = Nothing
Dim expression = TryCast(invocationExpression.Expression, MemberAccessExpressionSyntax).GetExpressionOfMemberAccessExpression()
' if it is via a base expression "MyBase.", we know the "throughType" is the base class but
' we need to be able to tell between "New Base().M()" and "MyBase.M()".
' currently, Access check methods do not differentiate between them.
' so handle "MyBase." primary-expression here by nulling out "throughType"
If expression IsNot Nothing AndAlso TypeOf expression IsNot MyBaseExpressionSyntax Then
throughType = semanticModel.GetTypeInfo(expression, cancellationToken).Type
End If
If TypeOf invocationExpression.Expression Is SimpleNameSyntax AndAlso
invocationExpression.IsInStaticContext() Then
memberGroup = memberGroup.Where(Function(m) m.IsStatic)
End If
Return memberGroup.Where(Function(m) m.IsAccessibleWithin(within, throughType)).ToImmutableArray()
End Function
Private Shared Function GetMemberGroupItems(accessibleMembers As ImmutableArray(Of ISymbol),
document As Document,
invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel) As IEnumerable(Of SignatureHelpItem)
If accessibleMembers.Length = 0 Then
Return SpecializedCollections.EmptyEnumerable(Of SignatureHelpItem)()
End If
Return accessibleMembers.Select(
Function(s) ConvertMemberGroupMember(document, s, invocationExpression.SpanStart, semanticModel))
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.SignatureHelp
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.SignatureHelp
Partial Friend Class InvocationExpressionSignatureHelpProvider
Private Shared Function GetAccessibleMembers(invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel,
within As ISymbol,
memberGroup As IEnumerable(Of ISymbol),
cancellationToken As CancellationToken) As ImmutableArray(Of ISymbol)
Dim throughType As ITypeSymbol = Nothing
Dim expression = TryCast(invocationExpression.Expression, MemberAccessExpressionSyntax).GetExpressionOfMemberAccessExpression()
' if it is via a base expression "MyBase.", we know the "throughType" is the base class but
' we need to be able to tell between "New Base().M()" and "MyBase.M()".
' currently, Access check methods do not differentiate between them.
' so handle "MyBase." primary-expression here by nulling out "throughType"
If expression IsNot Nothing AndAlso TypeOf expression IsNot MyBaseExpressionSyntax Then
throughType = semanticModel.GetTypeInfo(expression, cancellationToken).Type
End If
If TypeOf invocationExpression.Expression Is SimpleNameSyntax AndAlso
invocationExpression.IsInStaticContext() Then
memberGroup = memberGroup.Where(Function(m) m.IsStatic)
End If
Return memberGroup.Where(Function(m) m.IsAccessibleWithin(within, throughType)).ToImmutableArray()
End Function
Private Shared Function GetMemberGroupItems(accessibleMembers As ImmutableArray(Of ISymbol),
document As Document,
invocationExpression As InvocationExpressionSyntax,
semanticModel As SemanticModel) As IEnumerable(Of SignatureHelpItem)
If accessibleMembers.Length = 0 Then
Return SpecializedCollections.EmptyEnumerable(Of SignatureHelpItem)()
End If
Return accessibleMembers.Select(
Function(s) ConvertMemberGroupMember(document, s, invocationExpression.SpanStart, semanticModel))
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Analyzers/CSharp/Tests/UseThrowExpression/UseThrowExpressionTests_FixAllTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression
{
public partial class UseThrowExpressionTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument1()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInDocument:throw|} new ArgumentNullException(nameof(s));
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (t == null)
{
{|FixAllInDocument:throw|} new ArgumentNullException(nameof(t));
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument3()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInDocument:throw new ArgumentNullException(nameof(s));|}
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument4()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (t == null)
{
{|FixAllInDocument:throw new ArgumentNullException(nameof(t));|}
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocumentDoNotTouchOtherDocuments()
{
await TestInRegularAndScriptAsync(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInDocument:throw|} new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
</Project>
</Workspace>");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInProject1()
{
await TestInRegularAndScriptAsync(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInProject:throw|} new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}
</Document>
</Project>
</Workspace>");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseThrowExpression
{
public partial class UseThrowExpressionTests
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument1()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInDocument:throw|} new ArgumentNullException(nameof(s));
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument2()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (t == null)
{
{|FixAllInDocument:throw|} new ArgumentNullException(nameof(t));
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument3()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInDocument:throw new ArgumentNullException(nameof(s));|}
}
if (t == null)
{
throw new ArgumentNullException(nameof(t));
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocument4()
{
await TestInRegularAndScriptAsync(
@"using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
if (t == null)
{
{|FixAllInDocument:throw new ArgumentNullException(nameof(t));|}
}
_s = s;
_t = t;
}
}",
@"using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
_t = t ?? throw new ArgumentNullException(nameof(t));
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInDocumentDoNotTouchOtherDocuments()
{
await TestInRegularAndScriptAsync(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInDocument:throw|} new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
</Project>
</Workspace>");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseThrowExpression)]
public async Task FixAllInProject1()
{
await TestInRegularAndScriptAsync(
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
if (s == null)
{
{|FixAllInProject:throw|} new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
if (s == null)
{
throw new ArgumentNullException(nameof(s));
}
_s = s;
}
}
</Document>
</Project>
</Workspace>",
@"<Workspace>
<Project Language = ""C#"" AssemblyName=""Assembly1"" CommonReferences=""true"">
<Document>
using System;
class C
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}
</Document>
<Document>
using System;
class D
{
void M(string s, string t)
{
_s = s ?? throw new ArgumentNullException(nameof(s));
}
}
</Document>
</Project>
</Workspace>");
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/VisualStudio/Core/Test/CodeModel/VisualBasic/CodeStructTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class CodeStructTests
Inherits AbstractCodeStructTests
#Region "Parts tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParts1()
Dim code =
<Code>
Structure $$S
End Structure
</Code>
TestParts(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParts2()
Dim code =
<Code>
Partial Structure $$S
End Structure
</Code>
TestParts(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParts3()
Dim code =
<Code>
Partial Structure $$S
End Structure
Partial Structure S
End Structure
</Code>
TestParts(code, 2)
End Sub
#End Region
#Region "AddAttribute tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute1() As Task
Dim code =
<Code>
Imports System
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Imports System
<Serializable()>
Structure S
End Structure
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute2() As Task
Dim code =
<Code>
Imports System
<Serializable>
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Imports System
<Serializable>
<CLSCompliant(True)>
Structure S
End Structure
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_BelowDocComment() As Task
Dim code =
<Code>
Imports System
''' <summary></summary>
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Imports System
''' <summary></summary>
<CLSCompliant(True)>
Structure S
End Structure
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"})
End Function
#End Region
#Region "AddImplementedInterface tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddImplementedInterface1() As Task
Dim code =
<Code>
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I
End Structure
</Code>
Await TestAddImplementedInterface(code, "I", Nothing, expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddImplementedInterface2() As Task
Dim code =
<Code>
Structure $$S
Implements I
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements J
Implements I
End Structure
</Code>
Await TestAddImplementedInterface(code, "J", Nothing, expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddImplementedInterface3() As Task
Dim code =
<Code>
Structure $$S
Implements I
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I
Implements J
End Structure
</Code>
Await TestAddImplementedInterface(code, "J", -1, expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAddImplementedInterface4()
Dim code =
<Code>
Structure $$S
End Structure
</Code>
TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", 1)
End Sub
#End Region
#Region "RemoveImplementedInterface tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface1() As Task
Dim code =
<Code>
Structure $$S
Implements I
End Structure
</Code>
Dim expected =
<Code>
Structure S
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "I", expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestRemoveImplementedInterface2()
Dim code =
<Code>
Structure $$S
End Structure
</Code>
TestRemoveImplementedInterfaceThrows(Of COMException)(code, "I")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface3() As Task
Dim code =
<Code>
Structure $$S
Implements I, J
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "J", expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface4() As Task
Dim code =
<Code>
Structure $$S
Implements I, J
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements J
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "I", expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface5() As Task
Dim code =
<Code>
Structure $$S
Implements I, J, K
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I, K
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "J", expected)
End Function
#End Region
#Region "Set Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName1() As Task
Dim code =
<Code>
Structure $$Goo
End Structure
</Code>
Dim expected =
<Code>
Structure Bar
End Structure
</Code>
Await TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Function
#End Region
#Region "GenericExtender"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetBaseTypesCount()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetBaseTypesCount(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetBaseGenericName()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetBaseGenericName(code, 1, "System.ValueType")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplementedTypesCount1()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetImplementedTypesCount(code, 0)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplementedTypesCount2()
Dim code =
<Code>
Namespace N
Structure S$$
Implements IGoo(Of Integer)
End Structure
Interface IGoo(Of T)
End Interface
End Namespace
</Code>
TestGenericNameExtender_GetImplementedTypesCount(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplTypeGenericName1()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetImplTypeGenericName(code, 1, Nothing)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplTypeGenericName2()
Dim code =
<Code>
Namespace N
Structure S$$
Implements IGoo(Of Integer)
End Structure
Interface IGoo(Of T)
End Interface
End Namespace
</Code>
TestGenericNameExtender_GetImplTypeGenericName(code, 1, "N.IGoo(Of Integer)")
End Sub
#End Region
Private Function GetGenericExtender(codeElement As EnvDTE80.CodeStruct2) As IVBGenericExtender
Return CType(codeElement.Extender(ExtenderNames.VBGenericExtender), IVBGenericExtender)
End Function
Protected Overrides Function GenericNameExtender_GetBaseTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer
Return GetGenericExtender(codeElement).GetBaseTypesCount()
End Function
Protected Overrides Function GenericNameExtender_GetImplementedTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer
Return GetGenericExtender(codeElement).GetImplementedTypesCount()
End Function
Protected Overrides Function GenericNameExtender_GetBaseGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String
Return GetGenericExtender(codeElement).GetBaseGenericName(index)
End Function
Protected Overrides Function GenericNameExtender_GetImplTypeGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String
Return GetGenericExtender(codeElement).GetImplTypeGenericName(index)
End Function
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class CodeStructTests
Inherits AbstractCodeStructTests
#Region "Parts tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParts1()
Dim code =
<Code>
Structure $$S
End Structure
</Code>
TestParts(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParts2()
Dim code =
<Code>
Partial Structure $$S
End Structure
</Code>
TestParts(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestParts3()
Dim code =
<Code>
Partial Structure $$S
End Structure
Partial Structure S
End Structure
</Code>
TestParts(code, 2)
End Sub
#End Region
#Region "AddAttribute tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute1() As Task
Dim code =
<Code>
Imports System
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Imports System
<Serializable()>
Structure S
End Structure
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "Serializable"})
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute2() As Task
Dim code =
<Code>
Imports System
<Serializable>
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Imports System
<Serializable>
<CLSCompliant(True)>
Structure S
End Structure
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True", .Position = 1})
End Function
<WorkItem(2825, "https://github.com/dotnet/roslyn/issues/2825")>
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddAttribute_BelowDocComment() As Task
Dim code =
<Code>
Imports System
''' <summary></summary>
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Imports System
''' <summary></summary>
<CLSCompliant(True)>
Structure S
End Structure
</Code>
Await TestAddAttribute(code, expected, New AttributeData With {.Name = "CLSCompliant", .Value = "True"})
End Function
#End Region
#Region "AddImplementedInterface tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddImplementedInterface1() As Task
Dim code =
<Code>
Structure $$S
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I
End Structure
</Code>
Await TestAddImplementedInterface(code, "I", Nothing, expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddImplementedInterface2() As Task
Dim code =
<Code>
Structure $$S
Implements I
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements J
Implements I
End Structure
</Code>
Await TestAddImplementedInterface(code, "J", Nothing, expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestAddImplementedInterface3() As Task
Dim code =
<Code>
Structure $$S
Implements I
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I
Implements J
End Structure
</Code>
Await TestAddImplementedInterface(code, "J", -1, expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestAddImplementedInterface4()
Dim code =
<Code>
Structure $$S
End Structure
</Code>
TestAddImplementedInterfaceThrows(Of ArgumentException)(code, "I", 1)
End Sub
#End Region
#Region "RemoveImplementedInterface tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface1() As Task
Dim code =
<Code>
Structure $$S
Implements I
End Structure
</Code>
Dim expected =
<Code>
Structure S
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "I", expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestRemoveImplementedInterface2()
Dim code =
<Code>
Structure $$S
End Structure
</Code>
TestRemoveImplementedInterfaceThrows(Of COMException)(code, "I")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface3() As Task
Dim code =
<Code>
Structure $$S
Implements I, J
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "J", expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface4() As Task
Dim code =
<Code>
Structure $$S
Implements I, J
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements J
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "I", expected)
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestRemoveImplementedInterface5() As Task
Dim code =
<Code>
Structure $$S
Implements I, J, K
End Structure
</Code>
Dim expected =
<Code>
Structure S
Implements I, K
End Structure
</Code>
Await TestRemoveImplementedInterface(code, "J", expected)
End Function
#End Region
#Region "Set Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Async Function TestSetName1() As Task
Dim code =
<Code>
Structure $$Goo
End Structure
</Code>
Dim expected =
<Code>
Structure Bar
End Structure
</Code>
Await TestSetName(code, expected, "Bar", NoThrow(Of String)())
End Function
#End Region
#Region "GenericExtender"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetBaseTypesCount()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetBaseTypesCount(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetBaseGenericName()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetBaseGenericName(code, 1, "System.ValueType")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplementedTypesCount1()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetImplementedTypesCount(code, 0)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplementedTypesCount2()
Dim code =
<Code>
Namespace N
Structure S$$
Implements IGoo(Of Integer)
End Structure
Interface IGoo(Of T)
End Interface
End Namespace
</Code>
TestGenericNameExtender_GetImplementedTypesCount(code, 1)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplTypeGenericName1()
Dim code =
<Code>
Structure S$$
End Structure
</Code>
TestGenericNameExtender_GetImplTypeGenericName(code, 1, Nothing)
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestGenericExtender_GetImplTypeGenericName2()
Dim code =
<Code>
Namespace N
Structure S$$
Implements IGoo(Of Integer)
End Structure
Interface IGoo(Of T)
End Interface
End Namespace
</Code>
TestGenericNameExtender_GetImplTypeGenericName(code, 1, "N.IGoo(Of Integer)")
End Sub
#End Region
Private Function GetGenericExtender(codeElement As EnvDTE80.CodeStruct2) As IVBGenericExtender
Return CType(codeElement.Extender(ExtenderNames.VBGenericExtender), IVBGenericExtender)
End Function
Protected Overrides Function GenericNameExtender_GetBaseTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer
Return GetGenericExtender(codeElement).GetBaseTypesCount()
End Function
Protected Overrides Function GenericNameExtender_GetImplementedTypesCount(codeElement As EnvDTE80.CodeStruct2) As Integer
Return GetGenericExtender(codeElement).GetImplementedTypesCount()
End Function
Protected Overrides Function GenericNameExtender_GetBaseGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String
Return GetGenericExtender(codeElement).GetBaseGenericName(index)
End Function
Protected Overrides Function GenericNameExtender_GetImplTypeGenericName(codeElement As EnvDTE80.CodeStruct2, index As Integer) As String
Return GetGenericExtender(codeElement).GetImplTypeGenericName(index)
End Function
Protected Overrides ReadOnly Property LanguageName As String
Get
Return LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Compilers/VisualBasic/Portable/Symbols/MissingNamespaceSymbol.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Immutable
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports Binder = Microsoft.CodeAnalysis.VisualBasic.Binder
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A <see cref="MissingNamespaceSymbol"/> is a special kind of <see cref="NamespaceSymbol"/> that represents
''' a namespace that couldn't be found.
''' </summary>
Friend Class MissingNamespaceSymbol
Inherits NamespaceSymbol
Private ReadOnly _name As String
Private ReadOnly _containingSymbol As Symbol
Public Sub New(containingModule As MissingModuleSymbol)
Debug.Assert(containingModule IsNot Nothing)
_containingSymbol = containingModule
_name = String.Empty
End Sub
Public Sub New(containingNamespace As NamespaceSymbol, name As String)
Debug.Assert(containingNamespace IsNot Nothing)
Debug.Assert(name IsNot Nothing)
_containingSymbol = containingNamespace
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _containingSymbol
End Get
End Property
Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol
Get
Return _containingSymbol.ContainingAssembly
End Get
End Property
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
If _containingSymbol.Kind = SymbolKind.NetModule Then
Return New NamespaceExtent(DirectCast(_containingSymbol, ModuleSymbol))
End If
Return DirectCast(_containingSymbol, NamespaceSymbol).Extent
End Get
End Property
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode())
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If Me Is obj Then
Return True
End If
Dim other = TryCast(obj, MissingNamespaceSymbol)
Return other IsNot Nothing AndAlso String.Equals(_name, other._name, StringComparison.Ordinal) AndAlso _containingSymbol.Equals(other._containingSymbol)
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
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetModuleMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Friend Overrides ReadOnly Property DeclaredAccessibilityOfMostAccessibleDescendantType As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Friend Overrides Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol))
Return
End Sub
Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder,
appendThrough As NamespaceSymbol)
Return
End Sub
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Immutable
Imports System.Reflection
Imports System.Threading
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Utilities
Imports Binder = Microsoft.CodeAnalysis.VisualBasic.Binder
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A <see cref="MissingNamespaceSymbol"/> is a special kind of <see cref="NamespaceSymbol"/> that represents
''' a namespace that couldn't be found.
''' </summary>
Friend Class MissingNamespaceSymbol
Inherits NamespaceSymbol
Private ReadOnly _name As String
Private ReadOnly _containingSymbol As Symbol
Public Sub New(containingModule As MissingModuleSymbol)
Debug.Assert(containingModule IsNot Nothing)
_containingSymbol = containingModule
_name = String.Empty
End Sub
Public Sub New(containingNamespace As NamespaceSymbol, name As String)
Debug.Assert(containingNamespace IsNot Nothing)
Debug.Assert(name IsNot Nothing)
_containingSymbol = containingNamespace
_name = name
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _name
End Get
End Property
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _containingSymbol
End Get
End Property
Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol
Get
Return _containingSymbol.ContainingAssembly
End Get
End Property
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
If _containingSymbol.Kind = SymbolKind.NetModule Then
Return New NamespaceExtent(DirectCast(_containingSymbol, ModuleSymbol))
End If
Return DirectCast(_containingSymbol, NamespaceSymbol).Extent
End Get
End Property
Public Overrides Function GetHashCode() As Integer
Return Hash.Combine(_containingSymbol.GetHashCode(), _name.GetHashCode())
End Function
Public Overrides Function Equals(obj As Object) As Boolean
If Me Is obj Then
Return True
End If
Dim other = TryCast(obj, MissingNamespaceSymbol)
Return other IsNot Nothing AndAlso String.Equals(_name, other._name, StringComparison.Ordinal) AndAlso _containingSymbol.Equals(other._containingSymbol)
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
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetTypeMembers(name As String, arity As Integer) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetModuleMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return ImmutableArray(Of Symbol).Empty
End Function
Friend Overrides ReadOnly Property DeclaredAccessibilityOfMostAccessibleDescendantType As Accessibility
Get
Return Accessibility.Private
End Get
End Property
Friend Overrides Sub AppendProbableExtensionMethods(name As String, methods As ArrayBuilder(Of MethodSymbol))
Return
End Sub
Friend Overrides Sub AddExtensionMethodLookupSymbolsInfo(nameSet As LookupSymbolsInfo,
options As LookupOptions,
originalBinder As Binder,
appendThrough As NamespaceSymbol)
Return
End Sub
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./docs/analyzers/FixAllProvider.md | Introduction
============
This document covers the following:
- Introductory definitions
- What is a FixAll occurrences code fix?
- How is a FixAll occurrences code fix computed?
- Adding FixAll support to your code fixer
- Selecting an Equivalence key for code actions
- Spectrum of FixAll providers
- Built-in FixAllProvider and its limitations
- Implementing a custom FixAllProvider
Definitions
===========
- **Analyzer:** An instance of a type derived from `DiagnosticAnalyzer` that reports diagnostics.
- **Code fixer:** An instance of a type derived from `CodeFixProvider` that provides code fixes for compiler and/or analyzer diagnostics.
- **Code refactoring:** An instance of a type derived from `CodeRefactoringProvider` that provides source code refactorings.
- **Code action:** An action registered by `CodeFixProvider.RegisterCodeFixesAsync` that performs a code fix OR an action registered by `CodeRefactoringProvider.ComputeRefactoringsAsync` that performs a code refactoring.
- **Equivalence Key:** A string value representing an equivalence class of all code actions registered by a code fixer or refactoring. Two code actions are treated as equivalent if they have equal `EquivalenceKey` values and were generated by the same code fixer or refactoring.
- **FixAll provider:** An instance of a type derived from `FixAllProvider` that provides a FixAll occurrences code fix. A FixAll provider is associated with a corresponding code fixer by `CodeFixProvider.GetFixAllProvider` method.
- **FixAll occurrences code fix:** A code action returned by `FixAllProvider.GetFixAsync`, that fixes all or multiple occurrences of diagnostics fixed by the corresponding code fixer, within a given `FixAllScope`.
What is a FixAll occurrences code fix?
======================================
In layman terms, a FixAll occurrences code fix means: I have a code fix 'C', that fixes a specific instance of diagnostic 'D' in my source and I want to apply this fix to all instances of 'D' across a broader scope, such as a document or a project or the entire solution.
In more technical terms: Given a particular code action registered by a code fixer to fix one or more diagnostics, a corresponding code action registered by its FixAll provider, that applies the original trigger code action across a broader scope (such as a document/project/solution) to fix multiple instances of such diagnostics.
How is a FixAll occurrences code fix computed?
==============================================
Following steps are used to compute a FixAll occurrences code fix:
- Given a specific instance of a diagnostic, compute the set of code actions that claim to fix the diagnostic.
- Select a specific code action from this set. In the Visual Studio IDE, this is done by selecting a specific code action in the light bulb menu.
- The equivalence key of the selected code action represents the class of code actions that must be applied as part of a FixAll occurrences code fix.
- Given this code action, get the FixAll provider corresponding to the code fixer that registered this code action.
- If non-null, then request the FixAll provider for its supported FixAllScopes.
- Select a specific `FixAllScope` from this set. In the Visual Studio IDE, this is done by clicking on the scope hyperlink in the preview dialog.
- Given the trigger diagnostic(s), the equivalence key of the trigger code action, and the FixAll scope, invoke `FixAllProvider.GetFixAsync` to compute the FixAll occurrences code fix.
Adding FixAll support to your code fixer
========================================
Follow the below steps to add FixAll support to your code fixer:
- Override the `CodeFixProvider.GetFixAllProvider` method and return a non-null instance of a `FixAllProvider`. You may either use our built-in FixAllProvider or implement a custom FixAllProvider. See the following sections in this document for determining the correct approach for your fixer.
- Ensure that all the code actions registered by your code fixer have a non-null equivalence key. See the following section to determine how to select an equivalence key.
Selecting an Equivalence key for code actions
=============================================
Each unique equivalence key for a code fixer defines a unique equivalence class of code actions. Equivalence key of the trigger code action is part of the `FixAllContext` and is used to determine the FixAll occurrences code fix.
Normally, you can use the **'title'** of the code action as the equivalence key. However, there are cases where you may desire to have different values. Let us take an example to get a better understanding.
Let us consider the [C# SimplifyTypeNamesCodeFixProvider](https://github.com/dotnet/roslyn/blob/main/src/Features/CSharp/Portable/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs) that registers multiple code actions and also has FixAll support. This code fixer offers fixes to simplify the following expressions:
- `this` expressions of the form 'this.x' to 'x'.
- Qualified type names of the form 'A.B' to 'B'.
- Member access expressions of the form 'A.M' to 'M'.
This fixer needs the following semantics for the corresponding FixAll occurrences code fixes:
- `this` expression simplification: Fix all should simplify all this expressions, regardless of the member being accessed (this.x, this.y, this.z, etc.).
- Qualified type name simplification: Fix all should simplify all qualified type names 'A.B' to 'B'. However, we don't want to simplify **all** qualified type names, such as 'C.D', 'E.F', etc. as that would be too generic a fix, which is not likely intended by the user.
- Member access expressions: Fix all should simplify all member access expressions 'A.M' to 'M'.
It uses the below equivalence keys for its registered code actions to get the desired FixAll behavior:
- `this` expression simplification: Generic resource string "Simplify this expression", which explicitly excludes the contents of the node being simplified.
- Qualified type name simplification: Formatted resource string "Simplify type name A.B", which explicitly includes the contents of the node being simplified.
- Member access expressions: Formatted resource string "Simplify type name A.M", which explicitly includes the contents of the node being simplified.
Note that '`this` expression simplification' fix requires a different kind of an equivalence class from the other two simplifications. See method [GetCodeActionId](https://github.com/dotnet/roslyn/blob/main/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs) for the actual implementation.
To summarize, use the equivalence key that best suits the category of fixes to be applied as part of a FixAll operation.
Spectrum of FixAll providers
============================
When multiple fixes need to be applied to documents, there are various ways to do it:
- **Sequential approach**: One way to do it is to compute diagnostics, pick one, ask a fixer to produce a code action to fix that, apply it. Now for the resulting new compilation, recompute diagnostics, pick the next one and repeat the process. This approach would be very slow but would lead to correct results (unless it doesn't converge where one fix introduces a diagnostic that was just fixed by a previous fix). We chose to not implement this approach.
- **Batch fix approach**: Another way is to compute all the diagnostics, pick each diagnostic and give it to a fixer and apply it to produce a new solution. If there were 'n' diagnostics, there would be 'n' new solutions. Now just merge them all together in one go. This may produce incorrect results (when different fixes change the same region of code in different ways) but it is very fast. We have one implementation of this approach in `WellKnownFixAllProviders.BatchFixer`
- **Custom approach**: Depending on the fix, there may be a custom solution to fix multiple issues. For example, consider an analyzer that simply needs to generate one file as the fix for any instance of the issue. Instead of generating the same file over and over using the previous two approaches, one could write a custom `FixAllProvider` that simply generates the file once if there were any diagnostics at all.
Since there are various ways of fixing all issues, we've implemented a framework and provided the one general implementation that we think is useful in many cases.
Built-in FixAllProvider
=======================
We provide a default `BatchFixAllProvider` implementation of a FixAll provider that uses the underlying code fixer to compute the FixAll occurrences code fixes.
To use the batch fixer, you should return the static `WellKnownFixAllProviders.BatchFixer` instance in the `CodeFixProvider.GetFixAllProvider` override.
NOTE: See the following section on **'Limitations of the BatchFixer'** to determine if the batch fixer can be used by your code fixer.
Given a trigger diagnostic, a trigger code action, the underlying code fixer and the FixAll scope, the BatchFixer computes FixAll occurrences code fix with the following steps:
- Compute all instances of the trigger diagnostic across the FixAll scope.
- For each computed diagnostic, invoke the underlying code fixer to compute the set of code actions to fix the diagnostic.
- Collect all the registered code actions that have the same equivalence key as the trigger code action.
- Apply all these code actions on the original solution snapshot to compute new solution snapshots. The batch fixer only batches code action operations of type `ApplyChangesOperation` present within the individual code actions, other types of operations are ignored.
- Sequentially merge the new solution snapshots into a final solution snapshot. Only non-conflicting code actions whose fix spans don't overlap the fix spans of prior merged code actions are retained.
Limitations of the BatchFixer
=============================
The BatchFixer is designed for a common category of fixers where fix spans for diagnostics don't overlap with each other. For example, assume there is a diagnostic that spans a particular expression, and a fixer that fixes that expression. If all the instances of this diagnostic are guaranteed to have non-overlapping spans, then their fixes can be computed independently and this batch of fixes can be subsequently merged together.
However, there are cases where the BatchFixer might not work for your fixer. Following are some such examples:
- Code fixer registers code actions without an equivalence key or with a null equivalence key.
- Code fixer registers non-local code actions, i.e. a code action whose fix span is completely distinct from diagnostic span. For example, a fix that adds a new declaration node. Multiple such fixes are likely to have overlapping spans and hence could be conflicting.
- Diagnostics to be fixed as part of FixAll occurrences have overlapping spans. It is likely that fixes for such diagnostics will have overlapping spans too, and hence would conflict with each other.
- Code fixer registers code actions with operations other than `ApplyChangesOperation`. BatchFixer ignores such operations and hence may produce unexpected results.
Implementing a custom FixAllProvider
====================================
For cases where you cannot use the BatchFixer, you must implement your own `FixAllProvider`. It is recommended that you create a singleton instance of the FixAll provider, instead of creating a new instance for every `CodeFixProvider.GetFixAllProvider` invocation.
Following guidelines should help in the implementation:
- **GetFixAsync:** Primary method to compute the FixAll occurrences code fix for a given `FixAllContext`. You may use the set of 'GetXXXDiagnosticsAsync' methods on the `FixAllContext` to compute the diagnostics to be fixed. You must return a single code action that fixes all the diagnostics in the given FixAll scope.
- **GetSupportedFixAllScopes:** Virtual method to get all the supported FixAll scopes. By default, it returns all the three supported scopes: document, project and solution scopes. Generally, you need not override this method. However, you may do so if you wish to support a subset of these scopes.
- **GetSupportedFixAllDiagnosticIds:** Virtual method to get all the fixable diagnostic ids. By default, it returns the underlying code fixer's `FixableDiagnosticIds`. Generally, you need not override this method. However, you may do so if you wish to support FixAll only for a subset of these ids.
See [DeclarePublicAPIFix](https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs) for an example implementation of a custom FixAllProvider.
| Introduction
============
This document covers the following:
- Introductory definitions
- What is a FixAll occurrences code fix?
- How is a FixAll occurrences code fix computed?
- Adding FixAll support to your code fixer
- Selecting an Equivalence key for code actions
- Spectrum of FixAll providers
- Built-in FixAllProvider and its limitations
- Implementing a custom FixAllProvider
Definitions
===========
- **Analyzer:** An instance of a type derived from `DiagnosticAnalyzer` that reports diagnostics.
- **Code fixer:** An instance of a type derived from `CodeFixProvider` that provides code fixes for compiler and/or analyzer diagnostics.
- **Code refactoring:** An instance of a type derived from `CodeRefactoringProvider` that provides source code refactorings.
- **Code action:** An action registered by `CodeFixProvider.RegisterCodeFixesAsync` that performs a code fix OR an action registered by `CodeRefactoringProvider.ComputeRefactoringsAsync` that performs a code refactoring.
- **Equivalence Key:** A string value representing an equivalence class of all code actions registered by a code fixer or refactoring. Two code actions are treated as equivalent if they have equal `EquivalenceKey` values and were generated by the same code fixer or refactoring.
- **FixAll provider:** An instance of a type derived from `FixAllProvider` that provides a FixAll occurrences code fix. A FixAll provider is associated with a corresponding code fixer by `CodeFixProvider.GetFixAllProvider` method.
- **FixAll occurrences code fix:** A code action returned by `FixAllProvider.GetFixAsync`, that fixes all or multiple occurrences of diagnostics fixed by the corresponding code fixer, within a given `FixAllScope`.
What is a FixAll occurrences code fix?
======================================
In layman terms, a FixAll occurrences code fix means: I have a code fix 'C', that fixes a specific instance of diagnostic 'D' in my source and I want to apply this fix to all instances of 'D' across a broader scope, such as a document or a project or the entire solution.
In more technical terms: Given a particular code action registered by a code fixer to fix one or more diagnostics, a corresponding code action registered by its FixAll provider, that applies the original trigger code action across a broader scope (such as a document/project/solution) to fix multiple instances of such diagnostics.
How is a FixAll occurrences code fix computed?
==============================================
Following steps are used to compute a FixAll occurrences code fix:
- Given a specific instance of a diagnostic, compute the set of code actions that claim to fix the diagnostic.
- Select a specific code action from this set. In the Visual Studio IDE, this is done by selecting a specific code action in the light bulb menu.
- The equivalence key of the selected code action represents the class of code actions that must be applied as part of a FixAll occurrences code fix.
- Given this code action, get the FixAll provider corresponding to the code fixer that registered this code action.
- If non-null, then request the FixAll provider for its supported FixAllScopes.
- Select a specific `FixAllScope` from this set. In the Visual Studio IDE, this is done by clicking on the scope hyperlink in the preview dialog.
- Given the trigger diagnostic(s), the equivalence key of the trigger code action, and the FixAll scope, invoke `FixAllProvider.GetFixAsync` to compute the FixAll occurrences code fix.
Adding FixAll support to your code fixer
========================================
Follow the below steps to add FixAll support to your code fixer:
- Override the `CodeFixProvider.GetFixAllProvider` method and return a non-null instance of a `FixAllProvider`. You may either use our built-in FixAllProvider or implement a custom FixAllProvider. See the following sections in this document for determining the correct approach for your fixer.
- Ensure that all the code actions registered by your code fixer have a non-null equivalence key. See the following section to determine how to select an equivalence key.
Selecting an Equivalence key for code actions
=============================================
Each unique equivalence key for a code fixer defines a unique equivalence class of code actions. Equivalence key of the trigger code action is part of the `FixAllContext` and is used to determine the FixAll occurrences code fix.
Normally, you can use the **'title'** of the code action as the equivalence key. However, there are cases where you may desire to have different values. Let us take an example to get a better understanding.
Let us consider the [C# SimplifyTypeNamesCodeFixProvider](https://github.com/dotnet/roslyn/blob/main/src/Features/CSharp/Portable/SimplifyTypeNames/SimplifyTypeNamesCodeFixProvider.cs) that registers multiple code actions and also has FixAll support. This code fixer offers fixes to simplify the following expressions:
- `this` expressions of the form 'this.x' to 'x'.
- Qualified type names of the form 'A.B' to 'B'.
- Member access expressions of the form 'A.M' to 'M'.
This fixer needs the following semantics for the corresponding FixAll occurrences code fixes:
- `this` expression simplification: Fix all should simplify all this expressions, regardless of the member being accessed (this.x, this.y, this.z, etc.).
- Qualified type name simplification: Fix all should simplify all qualified type names 'A.B' to 'B'. However, we don't want to simplify **all** qualified type names, such as 'C.D', 'E.F', etc. as that would be too generic a fix, which is not likely intended by the user.
- Member access expressions: Fix all should simplify all member access expressions 'A.M' to 'M'.
It uses the below equivalence keys for its registered code actions to get the desired FixAll behavior:
- `this` expression simplification: Generic resource string "Simplify this expression", which explicitly excludes the contents of the node being simplified.
- Qualified type name simplification: Formatted resource string "Simplify type name A.B", which explicitly includes the contents of the node being simplified.
- Member access expressions: Formatted resource string "Simplify type name A.M", which explicitly includes the contents of the node being simplified.
Note that '`this` expression simplification' fix requires a different kind of an equivalence class from the other two simplifications. See method [GetCodeActionId](https://github.com/dotnet/roslyn/blob/main/src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs) for the actual implementation.
To summarize, use the equivalence key that best suits the category of fixes to be applied as part of a FixAll operation.
Spectrum of FixAll providers
============================
When multiple fixes need to be applied to documents, there are various ways to do it:
- **Sequential approach**: One way to do it is to compute diagnostics, pick one, ask a fixer to produce a code action to fix that, apply it. Now for the resulting new compilation, recompute diagnostics, pick the next one and repeat the process. This approach would be very slow but would lead to correct results (unless it doesn't converge where one fix introduces a diagnostic that was just fixed by a previous fix). We chose to not implement this approach.
- **Batch fix approach**: Another way is to compute all the diagnostics, pick each diagnostic and give it to a fixer and apply it to produce a new solution. If there were 'n' diagnostics, there would be 'n' new solutions. Now just merge them all together in one go. This may produce incorrect results (when different fixes change the same region of code in different ways) but it is very fast. We have one implementation of this approach in `WellKnownFixAllProviders.BatchFixer`
- **Custom approach**: Depending on the fix, there may be a custom solution to fix multiple issues. For example, consider an analyzer that simply needs to generate one file as the fix for any instance of the issue. Instead of generating the same file over and over using the previous two approaches, one could write a custom `FixAllProvider` that simply generates the file once if there were any diagnostics at all.
Since there are various ways of fixing all issues, we've implemented a framework and provided the one general implementation that we think is useful in many cases.
Built-in FixAllProvider
=======================
We provide a default `BatchFixAllProvider` implementation of a FixAll provider that uses the underlying code fixer to compute the FixAll occurrences code fixes.
To use the batch fixer, you should return the static `WellKnownFixAllProviders.BatchFixer` instance in the `CodeFixProvider.GetFixAllProvider` override.
NOTE: See the following section on **'Limitations of the BatchFixer'** to determine if the batch fixer can be used by your code fixer.
Given a trigger diagnostic, a trigger code action, the underlying code fixer and the FixAll scope, the BatchFixer computes FixAll occurrences code fix with the following steps:
- Compute all instances of the trigger diagnostic across the FixAll scope.
- For each computed diagnostic, invoke the underlying code fixer to compute the set of code actions to fix the diagnostic.
- Collect all the registered code actions that have the same equivalence key as the trigger code action.
- Apply all these code actions on the original solution snapshot to compute new solution snapshots. The batch fixer only batches code action operations of type `ApplyChangesOperation` present within the individual code actions, other types of operations are ignored.
- Sequentially merge the new solution snapshots into a final solution snapshot. Only non-conflicting code actions whose fix spans don't overlap the fix spans of prior merged code actions are retained.
Limitations of the BatchFixer
=============================
The BatchFixer is designed for a common category of fixers where fix spans for diagnostics don't overlap with each other. For example, assume there is a diagnostic that spans a particular expression, and a fixer that fixes that expression. If all the instances of this diagnostic are guaranteed to have non-overlapping spans, then their fixes can be computed independently and this batch of fixes can be subsequently merged together.
However, there are cases where the BatchFixer might not work for your fixer. Following are some such examples:
- Code fixer registers code actions without an equivalence key or with a null equivalence key.
- Code fixer registers non-local code actions, i.e. a code action whose fix span is completely distinct from diagnostic span. For example, a fix that adds a new declaration node. Multiple such fixes are likely to have overlapping spans and hence could be conflicting.
- Diagnostics to be fixed as part of FixAll occurrences have overlapping spans. It is likely that fixes for such diagnostics will have overlapping spans too, and hence would conflict with each other.
- Code fixer registers code actions with operations other than `ApplyChangesOperation`. BatchFixer ignores such operations and hence may produce unexpected results.
Implementing a custom FixAllProvider
====================================
For cases where you cannot use the BatchFixer, you must implement your own `FixAllProvider`. It is recommended that you create a singleton instance of the FixAll provider, instead of creating a new instance for every `CodeFixProvider.GetFixAllProvider` invocation.
Following guidelines should help in the implementation:
- **GetFixAsync:** Primary method to compute the FixAll occurrences code fix for a given `FixAllContext`. You may use the set of 'GetXXXDiagnosticsAsync' methods on the `FixAllContext` to compute the diagnostics to be fixed. You must return a single code action that fixes all the diagnostics in the given FixAll scope.
- **GetSupportedFixAllScopes:** Virtual method to get all the supported FixAll scopes. By default, it returns all the three supported scopes: document, project and solution scopes. Generally, you need not override this method. However, you may do so if you wish to support a subset of these scopes.
- **GetSupportedFixAllDiagnosticIds:** Virtual method to get all the fixable diagnostic ids. By default, it returns the underlying code fixer's `FixableDiagnosticIds`. Generally, you need not override this method. However, you may do so if you wish to support FixAll only for a subset of these ids.
See [DeclarePublicAPIFix](https://github.com/dotnet/roslyn-analyzers/blob/main/src/PublicApiAnalyzers/Core/CodeFixes/DeclarePublicApiFix.cs) for an example implementation of a custom FixAllProvider.
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/EditorFeatures/VisualBasicTest/SplitComment/SplitCommentCommandHandlerTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.SplitComment
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitComment
<UseExportProvider>
Public Class SplitCommentCommandHandlerTests
Inherits AbstractSplitCommentCommandHandlerTests
Protected Overrides Function CreateWorkspace(markup As String) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(markup)
End Function
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfComment()
TestHandled(
"Module Program
Sub Main(args As String())
'[||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
'
'Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfDoubleComment1()
TestHandled(
"Module Program
Sub Main(args As String())
''[||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
''
''Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfDoubleComment2()
TestHandled(
"Module Program
Sub Main(args As String())
'' [||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
''
'' Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfDoubleComment3()
TestHandled(
"Module Program
Sub Main(args As String())
''[||] Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
''
''Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfCommentWithLeadingSpace1()
TestHandled(
"Module Program
Sub Main(args As String())
' [||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
'
' Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfCommentWithLeadingSpace2()
TestHandled(
"Module Program
Sub Main(args As String())
'[||] Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
'
'Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitMiddleOfComment()
TestHandled(
"Module Program
Sub Main(args As String())
' Test [||]Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
' Test
' Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitEndOfComment()
TestNotHandled(
"Module Program
Sub Main(args As String())
' Test Comment[||]
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestNotAtEndOfFile()
TestNotHandled(
"Module Program
Sub Main(args As String())
' Test Comment[||]")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfMethod()
TestHandled(
"Module Program
Sub Main(args As String())
End Sub
' Test [||]Comment
End Module
",
"Module Program
Sub Main(args As String())
End Sub
' Test
' Comment
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfModule()
TestHandled(
"Module Program
Sub Main(args As String())
End Sub
End Module
' Test [||]Comment
",
"Module Program
Sub Main(args As String())
End Sub
End Module
' Test
' Comment
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfClass()
TestHandled(
"Class Program
Public Shared Sub Main(args As String())
End Sub
End Class
' Test [||]Comment
",
"Class Program
Public Shared Sub Main(args As String())
End Sub
End Class
' Test
' Comment
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfNamespace()
TestHandled(
"Namespace TestNamespace
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
' Test [||]Comment
",
"Namespace TestNamespace
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
' Test
' Comment
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentWithLineContinuation()
TestNotHandled(
"Module Program
Sub Main(args As String())
Dim X As Integer _ ' Comment [||]is here
= 4
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)>
<InlineData("X[||]Test Comment")>
<InlineData("X [||]Test Comment")>
<InlineData("X[||] Test Comment")>
<InlineData("X [||] Test Comment")>
Public Sub TestCommentWithMultipleLeadingSpaces(commentValue As String)
TestHandled(
$"public class Program
public sub Goo()
' {commentValue}
end sub
end class",
"public class Program
public sub Goo()
' X
' Test Comment
end sub
end class")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)>
<InlineData("X[||]Test Comment")>
<InlineData("X [||]Test Comment")>
<InlineData("X[||] Test Comment")>
<InlineData("X [||] Test Comment")>
Public Sub TestQuadCommentWithMultipleLeadingSpaces(commentValue As String)
TestHandled(
$"public class Program
public sub Goo()
'''' {commentValue}
end sub
end class",
"public class Program
public sub Goo()
'''' X
'''' Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards1()
TestNotHandled(
"public class Program
public sub Goo()
' goo[||] 'Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards2()
TestNotHandled(
"public class Program
{
public sub Goo()
{
' goo [||] 'Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards3()
TestNotHandled(
"public class Program
{
public sub Goo()
' goo [||]'Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards4()
TestNotHandled(
"public class Program
public sub Goo()
// [|goo|] 'Test Comment
end sub
end class")
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.Editor.UnitTests.SplitComment
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitComment
<UseExportProvider>
Public Class SplitCommentCommandHandlerTests
Inherits AbstractSplitCommentCommandHandlerTests
Protected Overrides Function CreateWorkspace(markup As String) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(markup)
End Function
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfComment()
TestHandled(
"Module Program
Sub Main(args As String())
'[||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
'
'Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfDoubleComment1()
TestHandled(
"Module Program
Sub Main(args As String())
''[||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
''
''Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfDoubleComment2()
TestHandled(
"Module Program
Sub Main(args As String())
'' [||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
''
'' Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfDoubleComment3()
TestHandled(
"Module Program
Sub Main(args As String())
''[||] Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
''
''Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfCommentWithLeadingSpace1()
TestHandled(
"Module Program
Sub Main(args As String())
' [||]Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
'
' Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitStartOfCommentWithLeadingSpace2()
TestHandled(
"Module Program
Sub Main(args As String())
'[||] Test Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
'
'Test Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitMiddleOfComment()
TestHandled(
"Module Program
Sub Main(args As String())
' Test [||]Comment
End Sub
End Module
",
"Module Program
Sub Main(args As String())
' Test
' Comment
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitEndOfComment()
TestNotHandled(
"Module Program
Sub Main(args As String())
' Test Comment[||]
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestNotAtEndOfFile()
TestNotHandled(
"Module Program
Sub Main(args As String())
' Test Comment[||]")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfMethod()
TestHandled(
"Module Program
Sub Main(args As String())
End Sub
' Test [||]Comment
End Module
",
"Module Program
Sub Main(args As String())
End Sub
' Test
' Comment
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfModule()
TestHandled(
"Module Program
Sub Main(args As String())
End Sub
End Module
' Test [||]Comment
",
"Module Program
Sub Main(args As String())
End Sub
End Module
' Test
' Comment
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfClass()
TestHandled(
"Class Program
Public Shared Sub Main(args As String())
End Sub
End Class
' Test [||]Comment
",
"Class Program
Public Shared Sub Main(args As String())
End Sub
End Class
' Test
' Comment
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentOutOfNamespace()
TestHandled(
"Namespace TestNamespace
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
' Test [||]Comment
",
"Namespace TestNamespace
Module Program
Sub Main(args As String())
End Sub
End Module
End Namespace
' Test
' Comment
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitCommentWithLineContinuation()
TestNotHandled(
"Module Program
Sub Main(args As String())
Dim X As Integer _ ' Comment [||]is here
= 4
End Sub
End Module
")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)>
<InlineData("X[||]Test Comment")>
<InlineData("X [||]Test Comment")>
<InlineData("X[||] Test Comment")>
<InlineData("X [||] Test Comment")>
Public Sub TestCommentWithMultipleLeadingSpaces(commentValue As String)
TestHandled(
$"public class Program
public sub Goo()
' {commentValue}
end sub
end class",
"public class Program
public sub Goo()
' X
' Test Comment
end sub
end class")
End Sub
<WorkItem(38516, "https://github.com/dotnet/roslyn/issues/38516")>
<WpfTheory, Trait(Traits.Feature, Traits.Features.SplitComment)>
<InlineData("X[||]Test Comment")>
<InlineData("X [||]Test Comment")>
<InlineData("X[||] Test Comment")>
<InlineData("X [||] Test Comment")>
Public Sub TestQuadCommentWithMultipleLeadingSpaces(commentValue As String)
TestHandled(
$"public class Program
public sub Goo()
'''' {commentValue}
end sub
end class",
"public class Program
public sub Goo()
'''' X
'''' Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards1()
TestNotHandled(
"public class Program
public sub Goo()
' goo[||] 'Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards2()
TestNotHandled(
"public class Program
{
public sub Goo()
{
' goo [||] 'Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards3()
TestNotHandled(
"public class Program
{
public sub Goo()
' goo [||]'Test Comment
end sub
end class")
End Sub
<WorkItem(48547, "https://github.com/dotnet/roslyn/issues/48547")>
<WpfFact, Trait(Traits.Feature, Traits.Features.SplitComment)>
Public Sub TestSplitWithCommentAfterwards4()
TestNotHandled(
"public class Program
public sub Goo()
// [|goo|] 'Test Comment
end sub
end class")
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Workspaces/Core/Portable/LinkedFileDiffMerging/IMergeConflictHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal interface IMergeConflictHandler
{
IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal interface IMergeConflictHandler
{
IEnumerable<TextChange> CreateEdits(SourceText originalSourceText, IEnumerable<UnmergedDocumentChanges> unmergedChanges);
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Workspaces/Core/Portable/Shared/Utilities/IStreamingProgressTrackerExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
internal static class IStreamingProgressTrackerExtensions
{
/// <summary>
/// Returns an <see cref="IAsyncDisposable"/> that will call <see
/// cref="IStreamingProgressTracker.ItemCompletedAsync"/> on <paramref
/// name="progressTracker"/> when it is disposed.
/// </summary>
public static async Task<IAsyncDisposable> AddSingleItemAsync(this IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
await progressTracker.AddItemsAsync(1, cancellationToken).ConfigureAwait(false);
return new StreamingProgressDisposer(progressTracker, cancellationToken);
}
private class StreamingProgressDisposer : IAsyncDisposable
{
private readonly IStreamingProgressTracker _progressTracker;
private readonly CancellationToken _cancellationToken;
public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
_progressTracker = progressTracker;
_cancellationToken = cancellationToken;
}
public async ValueTask DisposeAsync()
=> await _progressTracker.ItemCompletedAsync(_cancellationToken).ConfigureAwait(false);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class IStreamingProgressTrackerExtensions
{
/// <summary>
/// Returns an <see cref="IAsyncDisposable"/> that will call <see
/// cref="IStreamingProgressTracker.ItemCompletedAsync"/> on <paramref
/// name="progressTracker"/> when it is disposed.
/// </summary>
public static async Task<IAsyncDisposable> AddSingleItemAsync(this IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
await progressTracker.AddItemsAsync(1, cancellationToken).ConfigureAwait(false);
return new StreamingProgressDisposer(progressTracker, cancellationToken);
}
private class StreamingProgressDisposer : IAsyncDisposable
{
private readonly IStreamingProgressTracker _progressTracker;
private readonly CancellationToken _cancellationToken;
public StreamingProgressDisposer(IStreamingProgressTracker progressTracker, CancellationToken cancellationToken)
{
_progressTracker = progressTracker;
_cancellationToken = cancellationToken;
}
public async ValueTask DisposeAsync()
=> await _progressTracker.ItemCompletedAsync(_cancellationToken).ConfigureAwait(false);
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./docs/features/local-functions.work.md | Local Function Status
=====================
This is a checklist for current and outstanding work on the local functions
feature, as spec'd in [local-functions.md](./local-functions.md).
--------------------
Known issues
============
Compiler:
- [ ] Parser builds nodes for local functions when feature not enabled (#9940)
- [ ] Compiler crash: base call to state machine method, in state machine
method (#9872)
- [ ] Need custom warning for unused local function (#9661)
- [ ] Generate quick action does not offer to generate local (#9352)
- [ ] Parser ambiguity research (#10388)
- [ ] Dynamic support (#10389)
- [ ] Referring to local function in expression tree (#10390)
- [ ] Resolve definite assignment rules (#10391)
- [ ] Remove support for `var` return type (#10392)
- [ ] Update error messages (#10393)
IDE:
- [ ] Some selections around local functions fail extract method refactoring
[ ] (#8719)
- [ ] Extracting local function passed to an Action introduces compiler error
[ ] (#8718)
- [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717)
- [ ] Inline temp introductes compiler error (#8716)
- [ ] Call hierarchy search never terminates on local functions (#8654)
- [ ] Nav bar doesn't support local functions (#8648)
- [ ] No outlining for local functions (#8647)
- [ ] Squiggles all over the place when using an unsupported modifier (#8645)
- [ ] Peek definition errors out on local function (#8644)
- [ ] Void keyword not recommended while declaring local function (#8616)
- [ ] Change signature doesn't update the signature of the local function (#8539)
Feature Completeness Progress
=============================
- [x] N-level nested local functions
- [x] Capture
- Works alongside lambdas and behaves very similarly in fallback cases
- Has zero-allocation closures (struct frames by ref) on functions never
converted to a delegate and are not an iterator/async
- [x] Standard parameter features
- params
- ref/out
- named/optional
- [x] Visibility
- May revisit design (currently shadows, may do overloads)
- [x] Generics
- Nongeneric local functions in generic methods (same as lambdas).
- Generic local functions in nongeneric methods.
- Generic local functions in generic methods.
- Arbitrary nesting of generic local functions.
- Generic local functions with constraints.
- [x] Inferred return type
- [x] Iterators
- [x] Async
| Local Function Status
=====================
This is a checklist for current and outstanding work on the local functions
feature, as spec'd in [local-functions.md](./local-functions.md).
--------------------
Known issues
============
Compiler:
- [ ] Parser builds nodes for local functions when feature not enabled (#9940)
- [ ] Compiler crash: base call to state machine method, in state machine
method (#9872)
- [ ] Need custom warning for unused local function (#9661)
- [ ] Generate quick action does not offer to generate local (#9352)
- [ ] Parser ambiguity research (#10388)
- [ ] Dynamic support (#10389)
- [ ] Referring to local function in expression tree (#10390)
- [ ] Resolve definite assignment rules (#10391)
- [ ] Remove support for `var` return type (#10392)
- [ ] Update error messages (#10393)
IDE:
- [ ] Some selections around local functions fail extract method refactoring
[ ] (#8719)
- [ ] Extracting local function passed to an Action introduces compiler error
[ ] (#8718)
- [ ] Ctrl+. on a delegate invocation crashes VS (via Extract method) (#8717)
- [ ] Inline temp introductes compiler error (#8716)
- [ ] Call hierarchy search never terminates on local functions (#8654)
- [ ] Nav bar doesn't support local functions (#8648)
- [ ] No outlining for local functions (#8647)
- [ ] Squiggles all over the place when using an unsupported modifier (#8645)
- [ ] Peek definition errors out on local function (#8644)
- [ ] Void keyword not recommended while declaring local function (#8616)
- [ ] Change signature doesn't update the signature of the local function (#8539)
Feature Completeness Progress
=============================
- [x] N-level nested local functions
- [x] Capture
- Works alongside lambdas and behaves very similarly in fallback cases
- Has zero-allocation closures (struct frames by ref) on functions never
converted to a delegate and are not an iterator/async
- [x] Standard parameter features
- params
- ref/out
- named/optional
- [x] Visibility
- May revisit design (currently shadows, may do overloads)
- [x] Generics
- Nongeneric local functions in generic methods (same as lambdas).
- Generic local functions in nongeneric methods.
- Generic local functions in generic methods.
- Arbitrary nesting of generic local functions.
- Generic local functions with constraints.
- [x] Inferred return type
- [x] Iterators
- [x] Async
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Features/Core/Portable/SolutionCrawler/IDocumentDifferenceService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class DocumentDifferenceResult
{
public InvocationReasons ChangeType { get; }
public SyntaxNode? ChangedMember { get; }
public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null)
{
ChangeType = changeType;
ChangedMember = changedMember;
}
}
internal interface IDocumentDifferenceService : ILanguageService
{
Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
namespace Microsoft.CodeAnalysis.SolutionCrawler
{
internal class DocumentDifferenceResult
{
public InvocationReasons ChangeType { get; }
public SyntaxNode? ChangedMember { get; }
public DocumentDifferenceResult(InvocationReasons changeType, SyntaxNode? changedMember = null)
{
ChangeType = changeType;
ChangedMember = changedMember;
}
}
internal interface IDocumentDifferenceService : ILanguageService
{
Task<DocumentDifferenceResult?> GetDifferenceAsync(Document oldDocument, Document newDocument, CancellationToken cancellationToken);
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/VisualStudio/IntegrationTest/TestUtilities/Common/Comparison.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.VisualStudio.IntegrationTest.Utilities.Common
{
internal static class Comparison
{
public static bool AreStringValuesEqual(string? str1, string? str2)
=> (str1 ?? "") == (str2 ?? "");
public static bool AreArraysEqual<T>(T[]? array1, T[]? array2) where T : IEquatable<T>
{
if (array1 is null || array2 is null)
{
// both must be null
return array1 == array2;
}
if (array1.Length != array2.Length)
{
return false;
}
for (var i = 0; i < array1.Length; i++)
{
if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i]))
{
return false;
}
}
return true;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
namespace Microsoft.VisualStudio.IntegrationTest.Utilities.Common
{
internal static class Comparison
{
public static bool AreStringValuesEqual(string? str1, string? str2)
=> (str1 ?? "") == (str2 ?? "");
public static bool AreArraysEqual<T>(T[]? array1, T[]? array2) where T : IEquatable<T>
{
if (array1 is null || array2 is null)
{
// both must be null
return array1 == array2;
}
if (array1.Length != array2.Length)
{
return false;
}
for (var i = 0; i < array1.Length; i++)
{
if (!EqualityComparer<T>.Default.Equals(array1[i], array2[i]))
{
return false;
}
}
return true;
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/EditorFeatures/TestUtilities/EditAndContinue/ActiveStatementTestHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal static class ActiveStatementTestHelpers
{
public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp(
string[] markedSources,
string[]? filePaths = null,
int[]? methodRowIds = null,
Guid[]? modules = null,
int[]? methodVersions = null,
int[]? ilOffsets = null,
ActiveStatementFlags[]? flags = null)
{
return ActiveStatementsDescription.GetActiveStatementDebugInfos(
(source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path),
markedSources,
filePaths,
extension: ".cs",
methodRowIds,
modules,
methodVersions,
ilOffsets,
flags);
}
public static string Delete(string src, string marker)
{
while (true)
{
var startStr = "/*delete" + marker;
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length;
src = src.Substring(0, start) + src.Substring(end);
}
}
/// <summary>
/// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/.
/// </summary>
public static string InsertNewLines(string src, string marker)
{
while (true)
{
var startStr = "/*insert" + marker + "[";
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var startOfLineCount = start + startStr.Length;
var endOfLineCount = src.IndexOf(']', startOfLineCount);
var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount));
var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length;
src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end);
}
}
public static string Update(string src, string marker)
=> InsertNewLines(Delete(src, marker), marker);
public static string InspectActiveStatement(ActiveStatement statement)
=> $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]";
public static string InspectActiveStatementAndInstruction(ActiveStatement statement)
=> InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay();
public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text)
=> InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'";
public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update)
=> $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}";
public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions)
=> regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}");
public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r)
=> $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}";
public static string GetFirstLineText(LinePositionSpan span, SourceText text)
=> text.Lines[span.Start.Line].ToString().Trim();
public static string InspectSequencePointUpdates(SequencePointUpdates updates)
=> $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]";
public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates)
=> updates.Select(InspectSequencePointUpdates);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Microsoft.VisualStudio.Debugger.Contracts.EditAndContinue;
using Microsoft.CodeAnalysis.CSharp;
namespace Microsoft.CodeAnalysis.EditAndContinue.UnitTests
{
internal static class ActiveStatementTestHelpers
{
public static ImmutableArray<ManagedActiveStatementDebugInfo> GetActiveStatementDebugInfosCSharp(
string[] markedSources,
string[]? filePaths = null,
int[]? methodRowIds = null,
Guid[]? modules = null,
int[]? methodVersions = null,
int[]? ilOffsets = null,
ActiveStatementFlags[]? flags = null)
{
return ActiveStatementsDescription.GetActiveStatementDebugInfos(
(source, path) => SyntaxFactory.ParseSyntaxTree(source, path: path),
markedSources,
filePaths,
extension: ".cs",
methodRowIds,
modules,
methodVersions,
ilOffsets,
flags);
}
public static string Delete(string src, string marker)
{
while (true)
{
var startStr = "/*delete" + marker;
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var end = src.IndexOf(endStr, start + startStr.Length) + endStr.Length;
src = src.Substring(0, start) + src.Substring(end);
}
}
/// <summary>
/// Inserts new lines into the text at the position indicated by /*insert<paramref name="marker"/>[{number-of-lines-to-insert}]*/.
/// </summary>
public static string InsertNewLines(string src, string marker)
{
while (true)
{
var startStr = "/*insert" + marker + "[";
var endStr = "*/";
var start = src.IndexOf(startStr);
if (start == -1)
{
return src;
}
var startOfLineCount = start + startStr.Length;
var endOfLineCount = src.IndexOf(']', startOfLineCount);
var lineCount = int.Parse(src.Substring(startOfLineCount, endOfLineCount - startOfLineCount));
var end = src.IndexOf(endStr, endOfLineCount) + endStr.Length;
src = src.Substring(0, start) + string.Join("", Enumerable.Repeat(Environment.NewLine, lineCount)) + src.Substring(end);
}
}
public static string Update(string src, string marker)
=> InsertNewLines(Delete(src, marker), marker);
public static string InspectActiveStatement(ActiveStatement statement)
=> $"{statement.Ordinal}: {statement.FileSpan} flags=[{statement.Flags}]";
public static string InspectActiveStatementAndInstruction(ActiveStatement statement)
=> InspectActiveStatement(statement) + " " + statement.InstructionId.GetDebuggerDisplay();
public static string InspectActiveStatementAndInstruction(ActiveStatement statement, SourceText text)
=> InspectActiveStatementAndInstruction(statement) + $" '{GetFirstLineText(statement.Span, text)}'";
public static string InspectActiveStatementUpdate(ManagedActiveStatementUpdate update)
=> $"{update.Method.GetDebuggerDisplay()} IL_{update.ILOffset:X4}: {update.NewSpan.GetDebuggerDisplay()}";
public static IEnumerable<string> InspectNonRemappableRegions(ImmutableDictionary<ManagedMethodId, ImmutableArray<NonRemappableRegion>> regions)
=> regions.OrderBy(r => r.Key.Token).Select(r => $"{r.Key.Method.GetDebuggerDisplay()} | {string.Join(", ", r.Value.Select(r => r.GetDebuggerDisplay()))}");
public static string InspectExceptionRegionUpdate(ManagedExceptionRegionUpdate r)
=> $"{r.Method.GetDebuggerDisplay()} | {r.NewSpan.GetDebuggerDisplay()} Delta={r.Delta}";
public static string GetFirstLineText(LinePositionSpan span, SourceText text)
=> text.Lines[span.Start.Line].ToString().Trim();
public static string InspectSequencePointUpdates(SequencePointUpdates updates)
=> $"{updates.FileName}: [{string.Join(", ", updates.LineUpdates.Select(u => $"{u.OldLine} -> {u.NewLine}"))}]";
public static IEnumerable<string> Inspect(this IEnumerable<SequencePointUpdates> updates)
=> updates.Select(InspectSequencePointUpdates);
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/VisualStudio/Core/Def/Implementation/Snippets/IVsContainedLanguageHostInternal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// Redefine IVsContainedLanguageHost so we can call InsertImportsDirective which would
/// otherwise expect the namespace string as a ushort.
/// </summary>
[Guid("0429916F-69E1-4336-AB7E-72086FB0D6BC")]
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IVsContainedLanguageHostInternal
{
// These Reserved* methods are here to use up space in the vtable
void Reserved1();
void Reserved2();
void Reserved3();
void Reserved4();
void Reserved5();
void Reserved6();
void Reserved7();
void Reserved8();
void Reserved9();
void Reserved10();
void Reserved11();
void Reserved12();
[PreserveSig]
int InsertImportsDirective([MarshalAs(UnmanagedType.LPWStr)] string pwcImportP);
void Reserved13();
void Reserved14();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// Redefine IVsContainedLanguageHost so we can call InsertImportsDirective which would
/// otherwise expect the namespace string as a ushort.
/// </summary>
[Guid("0429916F-69E1-4336-AB7E-72086FB0D6BC")]
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
internal interface IVsContainedLanguageHostInternal
{
// These Reserved* methods are here to use up space in the vtable
void Reserved1();
void Reserved2();
void Reserved3();
void Reserved4();
void Reserved5();
void Reserved6();
void Reserved7();
void Reserved8();
void Reserved9();
void Reserved10();
void Reserved11();
void Reserved12();
[PreserveSig]
int InsertImportsDirective([MarshalAs(UnmanagedType.LPWStr)] string pwcImportP);
void Reserved13();
void Reserved14();
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/VisualBasic/LanguageServices/VisualBasicAddImportsService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.AddImports
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports
<ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicAddImportsService
Inherits AbstractAddImportsService(Of
CompilationUnitSyntax,
NamespaceBlockSyntax,
ImportsStatementSyntax,
ImportsStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer())
Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean
Dim importsA = TryCast(a, ImportsStatementSyntax)
Dim importsB = TryCast(b, ImportsStatementSyntax)
If importsA Is Nothing OrElse importsB Is Nothing Then
Return False
End If
Return ImportsStatementComparer.Compare(importsA, importsB) = 0
End Function
Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode)
Dim result = ArrayBuilder(Of SyntaxNode).GetInstance()
For Each import In compilation.MemberImports()
If TypeOf import Is INamespaceSymbol Then
result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString()))
End If
Next
Return result.ToImmutableAndFree()
End Function
Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode
Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax).
Where(Function(c) c.Alias IsNot Nothing).
FirstOrDefault()?.Alias
End Function
Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean
' Visual Basic doesn't support static imports
Return False
End Function
Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax)
If node.Kind() = SyntaxKind.CompilationUnit Then
Return DirectCast(node, CompilationUnitSyntax).Imports
End If
Return Nothing
End Function
Protected Overrides Function Rewrite(
externAliases() As ImportsStatementSyntax,
usingDirectives() As ImportsStatementSyntax,
staticUsingDirectives() As ImportsStatementSyntax,
aliasDirectives() As ImportsStatementSyntax,
externContainer As SyntaxNode,
usingContainer As SyntaxNode,
staticUsingContainer As SyntaxNode,
aliasContainer As SyntaxNode,
placeSystemNamespaceFirst As Boolean,
allowInHiddenRegions As Boolean,
root As SyntaxNode,
cancellationToken As CancellationToken) As SyntaxNode
Dim compilationUnit = DirectCast(root, CompilationUnitSyntax)
If Not compilationUnit.CanAddImportsStatements(allowInHiddenRegions, cancellationToken) Then
Return compilationUnit
End If
Return compilationUnit.AddImportsStatements(
usingDirectives.Concat(aliasDirectives).ToList(),
placeSystemNamespaceFirst,
Array.Empty(Of SyntaxAnnotation))
End Function
Private Class CaseInsensitiveTokenComparer
Implements IComparer(Of SyntaxToken)
Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare
' By using 'ValueText' we get the value that is normalized. i.e.
' [class] will be 'class', and unicode escapes will be converted
' to actual unicode. This allows sorting to work properly across
' tokens that have different source representations, but which
' mean the same thing.
' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens.
Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText())
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.AddImports
Imports Microsoft.CodeAnalysis.Editing
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.AddImports
<ExportLanguageService(GetType(IAddImportsService), LanguageNames.VisualBasic), [Shared]>
Friend Class VisualBasicAddImportsService
Inherits AbstractAddImportsService(Of
CompilationUnitSyntax,
NamespaceBlockSyntax,
ImportsStatementSyntax,
ImportsStatementSyntax)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Private Shared ReadOnly ImportsStatementComparer As ImportsStatementComparer = New ImportsStatementComparer(New CaseInsensitiveTokenComparer())
Protected Overrides Function IsEquivalentImport(a As SyntaxNode, b As SyntaxNode) As Boolean
Dim importsA = TryCast(a, ImportsStatementSyntax)
Dim importsB = TryCast(b, ImportsStatementSyntax)
If importsA Is Nothing OrElse importsB Is Nothing Then
Return False
End If
Return ImportsStatementComparer.Compare(importsA, importsB) = 0
End Function
Protected Overrides Function GetGlobalImports(compilation As Compilation, generator As SyntaxGenerator) As ImmutableArray(Of SyntaxNode)
Dim result = ArrayBuilder(Of SyntaxNode).GetInstance()
For Each import In compilation.MemberImports()
If TypeOf import Is INamespaceSymbol Then
result.Add(generator.NamespaceImportDeclaration(import.ToDisplayString()))
End If
Next
Return result.ToImmutableAndFree()
End Function
Protected Overrides Function GetAlias(usingOrAlias As ImportsStatementSyntax) As SyntaxNode
Return usingOrAlias.ImportsClauses.OfType(Of SimpleImportsClauseSyntax).
Where(Function(c) c.Alias IsNot Nothing).
FirstOrDefault()?.Alias
End Function
Protected Overrides Function IsStaticUsing(usingOrAlias As ImportsStatementSyntax) As Boolean
' Visual Basic doesn't support static imports
Return False
End Function
Protected Overrides Function GetExterns(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax)
Return Nothing
End Function
Protected Overrides Function GetUsingsAndAliases(node As SyntaxNode) As SyntaxList(Of ImportsStatementSyntax)
If node.Kind() = SyntaxKind.CompilationUnit Then
Return DirectCast(node, CompilationUnitSyntax).Imports
End If
Return Nothing
End Function
Protected Overrides Function Rewrite(
externAliases() As ImportsStatementSyntax,
usingDirectives() As ImportsStatementSyntax,
staticUsingDirectives() As ImportsStatementSyntax,
aliasDirectives() As ImportsStatementSyntax,
externContainer As SyntaxNode,
usingContainer As SyntaxNode,
staticUsingContainer As SyntaxNode,
aliasContainer As SyntaxNode,
placeSystemNamespaceFirst As Boolean,
allowInHiddenRegions As Boolean,
root As SyntaxNode,
cancellationToken As CancellationToken) As SyntaxNode
Dim compilationUnit = DirectCast(root, CompilationUnitSyntax)
If Not compilationUnit.CanAddImportsStatements(allowInHiddenRegions, cancellationToken) Then
Return compilationUnit
End If
Return compilationUnit.AddImportsStatements(
usingDirectives.Concat(aliasDirectives).ToList(),
placeSystemNamespaceFirst,
Array.Empty(Of SyntaxAnnotation))
End Function
Private Class CaseInsensitiveTokenComparer
Implements IComparer(Of SyntaxToken)
Public Function Compare(x As SyntaxToken, y As SyntaxToken) As Integer Implements IComparer(Of SyntaxToken).Compare
' By using 'ValueText' we get the value that is normalized. i.e.
' [class] will be 'class', and unicode escapes will be converted
' to actual unicode. This allows sorting to work properly across
' tokens that have different source representations, but which
' mean the same thing.
' Don't bother checking the raw kind, since this will only ever be used with Identifier tokens.
Return CaseInsensitiveComparer.Default.Compare(x.GetIdentifierText(), y.GetIdentifierText())
End Function
End Class
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/FixAllProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Implement this abstract type to provide fix all/multiple occurrences code fixes for source code problems.
/// Alternatively, you can use any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/>.
/// </summary>
public abstract class FixAllProvider
{
/// <summary>
/// Gets the supported scopes for fixing all occurrences of a diagnostic.
/// By default, it returns the following scopes:
/// (a) <see cref="FixAllScope.Document"/>
/// (b) <see cref="FixAllScope.Project"/> and
/// (c) <see cref="FixAllScope.Solution"/>
/// </summary>
public virtual IEnumerable<FixAllScope> GetSupportedFixAllScopes()
=> ImmutableArray.Create(FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution);
/// <summary>
/// Gets the diagnostic IDs for which fix all occurrences is supported.
/// By default, it returns <see cref="CodeFixProvider.FixableDiagnosticIds"/> for the given <paramref name="originalCodeFixProvider"/>.
/// </summary>
/// <param name="originalCodeFixProvider">Original code fix provider that returned this fix all provider from <see cref="CodeFixProvider.GetFixAllProvider"/> method.</param>
public virtual IEnumerable<string> GetSupportedFixAllDiagnosticIds(CodeFixProvider originalCodeFixProvider)
=> originalCodeFixProvider.FixableDiagnosticIds;
/// <summary>
/// Gets fix all occurrences fix for the given fixAllContext.
/// </summary>
public abstract Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext);
/// <summary>
/// Create a <see cref="FixAllProvider"/> that fixes documents independently. This should be used instead of
/// <see cref="WellKnownFixAllProviders.BatchFixer"/> in the case where fixes for a <see cref="Diagnostic"/>
/// only affect the <see cref="Document"/> the diagnostic was produced in.
/// </summary>
/// <param name="fixAllAsync">
/// Callback that will the fix diagnostics present in the provided document. The document returned will only be
/// examined for its content (e.g. it's <see cref="SyntaxTree"/> or <see cref="SourceText"/>. No other aspects
/// of it (like attributes), or changes to the <see cref="Project"/> or <see cref="Solution"/> it points at
/// will be considered.
/// </param>
public static FixAllProvider Create(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync)
{
if (fixAllAsync == null)
throw new ArgumentNullException(nameof(fixAllAsync));
return new CallbackDocumentBasedFixAllProvider(fixAllAsync);
}
private class CallbackDocumentBasedFixAllProvider : DocumentBasedFixAllProvider
{
private readonly Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> _fixAllAsync;
public CallbackDocumentBasedFixAllProvider(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync)
{
_fixAllAsync = fixAllAsync;
}
protected override Task<Document?> FixAllAsync(FixAllContext context, Document document, ImmutableArray<Diagnostic> diagnostics)
=> _fixAllAsync(context, document, diagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CodeFixes
{
/// <summary>
/// Implement this abstract type to provide fix all/multiple occurrences code fixes for source code problems.
/// Alternatively, you can use any of the well known fix all providers from <see cref="WellKnownFixAllProviders"/>.
/// </summary>
public abstract class FixAllProvider
{
/// <summary>
/// Gets the supported scopes for fixing all occurrences of a diagnostic.
/// By default, it returns the following scopes:
/// (a) <see cref="FixAllScope.Document"/>
/// (b) <see cref="FixAllScope.Project"/> and
/// (c) <see cref="FixAllScope.Solution"/>
/// </summary>
public virtual IEnumerable<FixAllScope> GetSupportedFixAllScopes()
=> ImmutableArray.Create(FixAllScope.Document, FixAllScope.Project, FixAllScope.Solution);
/// <summary>
/// Gets the diagnostic IDs for which fix all occurrences is supported.
/// By default, it returns <see cref="CodeFixProvider.FixableDiagnosticIds"/> for the given <paramref name="originalCodeFixProvider"/>.
/// </summary>
/// <param name="originalCodeFixProvider">Original code fix provider that returned this fix all provider from <see cref="CodeFixProvider.GetFixAllProvider"/> method.</param>
public virtual IEnumerable<string> GetSupportedFixAllDiagnosticIds(CodeFixProvider originalCodeFixProvider)
=> originalCodeFixProvider.FixableDiagnosticIds;
/// <summary>
/// Gets fix all occurrences fix for the given fixAllContext.
/// </summary>
public abstract Task<CodeAction?> GetFixAsync(FixAllContext fixAllContext);
/// <summary>
/// Create a <see cref="FixAllProvider"/> that fixes documents independently. This should be used instead of
/// <see cref="WellKnownFixAllProviders.BatchFixer"/> in the case where fixes for a <see cref="Diagnostic"/>
/// only affect the <see cref="Document"/> the diagnostic was produced in.
/// </summary>
/// <param name="fixAllAsync">
/// Callback that will the fix diagnostics present in the provided document. The document returned will only be
/// examined for its content (e.g. it's <see cref="SyntaxTree"/> or <see cref="SourceText"/>. No other aspects
/// of it (like attributes), or changes to the <see cref="Project"/> or <see cref="Solution"/> it points at
/// will be considered.
/// </param>
public static FixAllProvider Create(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync)
{
if (fixAllAsync == null)
throw new ArgumentNullException(nameof(fixAllAsync));
return new CallbackDocumentBasedFixAllProvider(fixAllAsync);
}
private class CallbackDocumentBasedFixAllProvider : DocumentBasedFixAllProvider
{
private readonly Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> _fixAllAsync;
public CallbackDocumentBasedFixAllProvider(Func<FixAllContext, Document, ImmutableArray<Diagnostic>, Task<Document?>> fixAllAsync)
{
_fixAllAsync = fixAllAsync;
}
protected override Task<Document?> FixAllAsync(FixAllContext context, Document document, ImmutableArray<Diagnostic> diagnostics)
=> _fixAllAsync(context, document, diagnostics);
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Compilers/CSharp/Test/Symbol/Compilation/GetUnusedImportDirectivesTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class GetUnusedImportDirectivesTests : SemanticModelTestBase
{
[Fact]
public void UnusedUsing1()
{
var text = @"
using System;
class C
{
void Goo()
{
}
}";
var tree = Parse(text);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
}
[WorkItem(865627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865627")]
[Fact]
public void TestUnusedExtensionMarksImportsAsUsed()
{
string class1Source = @"using System;
namespace ClassLibrary1
{
public class Class1
{
public void Method1(string arg1)
{
Console.WriteLine(arg1);
}
}
}
";
var classLib1 = CreateCompilation(source: class1Source, assemblyName: "ClassLibrary1");
string class2Source = @"using System;
using ClassLibrary1;
namespace ClassLibrary2
{
public static class Class2
{
public static void Method1(this Class1 arg0, string arg1)
{
Console.Write(""Erroneous: "" + arg1);
}
}
}";
var classLib2 = CreateCompilation(source: class2Source, assemblyName: "ClassLibrary2", references: new[] { classLib1.ToMetadataReference() });
string consoleApplicationSource = @"using ClassLibrary2;
using ClassLibrary1;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var instance1 = new Class1();
instance1.Method1(""Argument1"");
}
}
}";
var tree = Parse(consoleApplicationSource);
var comp = CreateCompilation(tree, new[] { classLib1.ToMetadataReference(), classLib2.ToMetadataReference() }, assemblyName: "ConsoleApplication");
var model = comp.GetSemanticModel(tree) as CSharpSemanticModel;
var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression;
//This is the crux of the test.
//Without this line, with or without the fix, the model never gets pushed to evaluate extension method candidates
//and therefore never marked ClassLibrary2 as a used import in consoleApplication.
//Without the fix, this call used to result in ClassLibrary2 getting marked as used, after the fix, this call does not
//result in changing ClassLibrary2's used status.
model.GetMemberGroup(syntax);
model.GetDiagnostics().Verify(Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ClassLibrary2;"));
}
[WorkItem(747219, "DevDiv2/DevDiv")]
[Fact]
public void UnusedUsing747219()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Enumerable.Repeat(1, 1);
}
}";
var comp = CreateEmptyCompilation(text, new[] { MscorlibRef });
//all unused because system.core was not included and Enumerable didn't bind
comp.VerifyDiagnostics(
// (4,14): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
// using System.Linq;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Linq").WithArguments("Linq", "System"),
// (11,9): error CS0103: The name 'Enumerable' does not exist in the current context
// Enumerable.Repeat(1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Enumerable").WithArguments("Enumerable"),
// (4,1): info CS8019: Unnecessary using directive.
// using System.Linq;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"),
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"),
// (5,1): info CS8019: Unnecessary using directive.
// using System.Threading.Tasks;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;")
);
comp = comp.WithReferences(comp.References.Concat(SystemCoreRef));
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"),
// (5,1): info CS8019: Unnecessary using directive.
// using System.Threading.Tasks;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;")
);
}
[Fact]
public void UsedUsing1()
{
var text = @"
using System;
class C
{
void Goo()
{
Console.WriteLine();
}
}";
var tree = Parse(text);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics();
}
[Fact]
public void SpeculativeBindingDoesNotAffectResult()
{
var text = @"
using System;
class C
{
void Goo()
{
/*here*/
}
}";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var position = text.IndexOf("/*here*/", StringComparison.Ordinal);
var info = model.GetSpeculativeSymbolInfo(position, SyntaxFactory.IdentifierName("Console"), SpeculativeBindingOption.BindAsTypeOrNamespace);
Assert.NotNull(info.Symbol);
Assert.Equal(SymbolKind.NamedType, info.Symbol.Kind);
Assert.Equal("Console", info.Symbol.Name);
Assert.Equal(SymbolKind.Namespace, info.Symbol.ContainingSymbol.Kind);
Assert.Equal("System", info.Symbol.ContainingSymbol.Name);
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")
);
}
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void AllAssemblyLevelAttributesMustBeBound()
{
var snkPath = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey).Path;
var signing = Parse(@"
using System.Reflection;
[assembly: AssemblyVersion(""1.2.3.4"")]
[assembly: AssemblyKeyFile(@""" + snkPath + @""")]
");
var ivtCompilation = CreateCompilation(
assemblyName: "IVT",
options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()),
source: new[]
{
Parse(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Lib, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
namespace NamespaceContainingInternalsOnly
{
internal static class Extensions
{
internal static void Goo(this int x) {}
}
}
"),
signing
});
var libCompilation = CreateCompilation(
assemblyName: "Lib",
options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()),
references: new[] { ivtCompilation.ToMetadataReference() },
source: new[]
{
Parse(@"
using NamespaceContainingInternalsOnly;
public class C
{
internal static void F(int x)
{
x.Goo();
}
}
"),
signing
});
libCompilation.VerifyDiagnostics();
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void SemanticModelCallDoesNotCountsAsUse()
{
var source = @"
using System.Collections;
using System.Collections.Generic;
class C
{
void M()
{
return;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Collections;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;")
);
comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(3));
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Collections;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;")
);
}
[Fact]
public void NoHiddenDiagnosticsForWarningLevel0()
{
var source = @"
using System.Collections;
using System.Collections.Generic;
class C
{
void M()
{
return;
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0));
comp.VerifyDiagnostics();
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void INF_UnusedUsingDirective()
{
var source = @"
using System.Collections;
using C = System.Console;
";
CreateCompilation(source).VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Collections;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"),
// (3,1): info CS8019: Unnecessary using directive.
// using C = System.Console;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using C = System.Console;"));
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void INF_UnusedExternAlias()
{
var source = @"
extern alias A;
";
var lib = CreateEmptyCompilation("", assemblyName: "lib");
var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("A")) });
comp.VerifyDiagnostics(
// (2,1): info CS8020: Unused extern alias.
// extern alias A;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;"));
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void CrefCountsAsUse()
{
var source = @"
using System;
/// <see cref='Console'/>
public class C { }
";
// Not reporting doc comment diagnostics. It is still a use.
CreateCompilation(source).VerifyDiagnostics();
// Binding doc comments.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics();
}
[WorkItem(770147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770147")]
[Fact]
public void InfoAndWarnAsError()
{
var source = @"
using System;
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error));
comp.VerifyEmitDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithWarningAsError(false));
}
[Fact]
public void UnusedUsingInteractive()
{
var tree = Parse("using System;", options: TestOptions.Script);
var comp = CSharpCompilation.CreateScriptCompilation("sub1", tree, new[] { MscorlibRef_v4_0_30316_17626 });
comp.VerifyDiagnostics();
}
[Fact]
public void UnusedUsingScript()
{
var tree = Parse("using System;", options: TestOptions.Script);
var comp = CreateCompilationWithMscorlib45(new[] { tree });
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
}
[Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")]
public void IncorrectUnusedUsingWhenAttributeOnParameter_01()
{
var source1 =
@"using System.Runtime.InteropServices;
partial class Program
{
partial void M([Out] [In] ref int x) { }
}";
var source2 =
@"partial class Program
{
partial void M(ref int x);
}";
var comp = CreateCompilation(new[] { source1, source2 });
var tree = comp.SyntaxTrees[0];
//comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug
var model = comp.GetSemanticModel(tree);
// There should be no diagnostics.
model.GetDiagnostics().Verify(
//// (1,1): hidden CS8019: Unnecessary using directive.
//// using System.Runtime.InteropServices;
//Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1)
);
}
[Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")]
public void IncorrectUnusedUsingWhenAttributeOnParameter_02()
{
var source1 =
@"using System.Runtime.InteropServices;
partial class Program
{
partial void M([Out] [In] ref int x);
}";
var source2 =
@"partial class Program
{
partial void M(ref int x) { }
}";
var comp = CreateCompilation(new[] { source1, source2 });
var tree = comp.SyntaxTrees[0];
//comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug
var model = comp.GetSemanticModel(tree);
// There should be no diagnostics.
model.GetDiagnostics().Verify(
//// (1,1): hidden CS8019: Unnecessary using directive.
//// using System.Runtime.InteropServices;
//Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1)
);
}
[Fact, WorkItem(2773, "https://github.com/dotnet/roslyn/issues/2773")]
public void UsageInDocComment()
{
var source = @"using X;
/// <summary/>
public class Program
{
/// <summary>
/// <see cref=""Q""/>
/// </summary>
static void Main(string[] args)
{
}
}
namespace X
{
/// <summary/>
public class Q { }
}
";
foreach (DocumentationMode documentationMode in Enum.GetValues(typeof(DocumentationMode)))
{
var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithDocumentationMode(documentationMode));
compilation.VerifyDiagnostics();
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class GetUnusedImportDirectivesTests : SemanticModelTestBase
{
[Fact]
public void UnusedUsing1()
{
var text = @"
using System;
class C
{
void Goo()
{
}
}";
var tree = Parse(text);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
}
[WorkItem(865627, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/865627")]
[Fact]
public void TestUnusedExtensionMarksImportsAsUsed()
{
string class1Source = @"using System;
namespace ClassLibrary1
{
public class Class1
{
public void Method1(string arg1)
{
Console.WriteLine(arg1);
}
}
}
";
var classLib1 = CreateCompilation(source: class1Source, assemblyName: "ClassLibrary1");
string class2Source = @"using System;
using ClassLibrary1;
namespace ClassLibrary2
{
public static class Class2
{
public static void Method1(this Class1 arg0, string arg1)
{
Console.Write(""Erroneous: "" + arg1);
}
}
}";
var classLib2 = CreateCompilation(source: class2Source, assemblyName: "ClassLibrary2", references: new[] { classLib1.ToMetadataReference() });
string consoleApplicationSource = @"using ClassLibrary2;
using ClassLibrary1;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
var instance1 = new Class1();
instance1.Method1(""Argument1"");
}
}
}";
var tree = Parse(consoleApplicationSource);
var comp = CreateCompilation(tree, new[] { classLib1.ToMetadataReference(), classLib2.ToMetadataReference() }, assemblyName: "ConsoleApplication");
var model = comp.GetSemanticModel(tree) as CSharpSemanticModel;
var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single().Expression;
//This is the crux of the test.
//Without this line, with or without the fix, the model never gets pushed to evaluate extension method candidates
//and therefore never marked ClassLibrary2 as a used import in consoleApplication.
//Without the fix, this call used to result in ClassLibrary2 getting marked as used, after the fix, this call does not
//result in changing ClassLibrary2's used status.
model.GetMemberGroup(syntax);
model.GetDiagnostics().Verify(Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using ClassLibrary2;"));
}
[WorkItem(747219, "DevDiv2/DevDiv")]
[Fact]
public void UnusedUsing747219()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Enumerable.Repeat(1, 1);
}
}";
var comp = CreateEmptyCompilation(text, new[] { MscorlibRef });
//all unused because system.core was not included and Enumerable didn't bind
comp.VerifyDiagnostics(
// (4,14): error CS0234: The type or namespace name 'Linq' does not exist in the namespace 'System' (are you missing an assembly reference?)
// using System.Linq;
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Linq").WithArguments("Linq", "System"),
// (11,9): error CS0103: The name 'Enumerable' does not exist in the current context
// Enumerable.Repeat(1, 1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "Enumerable").WithArguments("Enumerable"),
// (4,1): info CS8019: Unnecessary using directive.
// using System.Linq;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"),
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"),
// (5,1): info CS8019: Unnecessary using directive.
// using System.Threading.Tasks;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;")
);
comp = comp.WithReferences(comp.References.Concat(SystemCoreRef));
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;"),
// (5,1): info CS8019: Unnecessary using directive.
// using System.Threading.Tasks;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Threading.Tasks;")
);
}
[Fact]
public void UsedUsing1()
{
var text = @"
using System;
class C
{
void Goo()
{
Console.WriteLine();
}
}";
var tree = Parse(text);
var comp = CreateCompilation(tree);
comp.VerifyDiagnostics();
}
[Fact]
public void SpeculativeBindingDoesNotAffectResult()
{
var text = @"
using System;
class C
{
void Goo()
{
/*here*/
}
}";
var tree = Parse(text);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var position = text.IndexOf("/*here*/", StringComparison.Ordinal);
var info = model.GetSpeculativeSymbolInfo(position, SyntaxFactory.IdentifierName("Console"), SpeculativeBindingOption.BindAsTypeOrNamespace);
Assert.NotNull(info.Symbol);
Assert.Equal(SymbolKind.NamedType, info.Symbol.Kind);
Assert.Equal("Console", info.Symbol.Name);
Assert.Equal(SymbolKind.Namespace, info.Symbol.ContainingSymbol.Kind);
Assert.Equal("System", info.Symbol.ContainingSymbol.Name);
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;")
);
}
[ClrOnlyFact(ClrOnlyReason.Unknown)]
public void AllAssemblyLevelAttributesMustBeBound()
{
var snkPath = Temp.CreateFile().WriteAllBytes(TestResources.General.snKey).Path;
var signing = Parse(@"
using System.Reflection;
[assembly: AssemblyVersion(""1.2.3.4"")]
[assembly: AssemblyKeyFile(@""" + snkPath + @""")]
");
var ivtCompilation = CreateCompilation(
assemblyName: "IVT",
options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()),
source: new[]
{
Parse(@"
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo(""Lib, PublicKey=00240000048000009400000006020000002400005253413100040000010001002b986f6b5ea5717d35c72d38561f413e267029efa9b5f107b9331d83df657381325b3a67b75812f63a9436ceccb49494de8f574f8e639d4d26c0fcf8b0e9a1a196b80b6f6ed053628d10d027e032df2ed1d60835e5f47d32c9ef6da10d0366a319573362c821b5f8fa5abc5bb22241de6f666a85d82d6ba8c3090d01636bd2bb"")]
namespace NamespaceContainingInternalsOnly
{
internal static class Extensions
{
internal static void Goo(this int x) {}
}
}
"),
signing
});
var libCompilation = CreateCompilation(
assemblyName: "Lib",
options: TestOptions.ReleaseDll.WithStrongNameProvider(new DesktopStrongNameProvider()),
references: new[] { ivtCompilation.ToMetadataReference() },
source: new[]
{
Parse(@"
using NamespaceContainingInternalsOnly;
public class C
{
internal static void F(int x)
{
x.Goo();
}
}
"),
signing
});
libCompilation.VerifyDiagnostics();
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void SemanticModelCallDoesNotCountsAsUse()
{
var source = @"
using System.Collections;
using System.Collections.Generic;
class C
{
void M()
{
return;
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Collections;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;")
);
comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(3));
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Collections;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"),
// (3,1): info CS8019: Unnecessary using directive.
// using System.Collections.Generic;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;")
);
}
[Fact]
public void NoHiddenDiagnosticsForWarningLevel0()
{
var source = @"
using System.Collections;
using System.Collections.Generic;
class C
{
void M()
{
return;
}
}";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithWarningLevel(0));
comp.VerifyDiagnostics();
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void INF_UnusedUsingDirective()
{
var source = @"
using System.Collections;
using C = System.Console;
";
CreateCompilation(source).VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Collections;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections;"),
// (3,1): info CS8019: Unnecessary using directive.
// using C = System.Console;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using C = System.Console;"));
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void INF_UnusedExternAlias()
{
var source = @"
extern alias A;
";
var lib = CreateEmptyCompilation("", assemblyName: "lib");
var comp = CreateCompilation(source, new[] { new CSharpCompilationReference(lib, aliases: ImmutableArray.Create("A")) });
comp.VerifyDiagnostics(
// (2,1): info CS8020: Unused extern alias.
// extern alias A;
Diagnostic(ErrorCode.HDN_UnusedExternAlias, "extern alias A;"));
}
[WorkItem(747219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747219")]
[Fact]
public void CrefCountsAsUse()
{
var source = @"
using System;
/// <see cref='Console'/>
public class C { }
";
// Not reporting doc comment diagnostics. It is still a use.
CreateCompilation(source).VerifyDiagnostics();
// Binding doc comments.
CreateCompilationWithMscorlib40AndDocumentationComments(source).VerifyDiagnostics();
}
[WorkItem(770147, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/770147")]
[Fact]
public void InfoAndWarnAsError()
{
var source = @"
using System;
";
var comp = CreateCompilation(source, options: TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error));
comp.VerifyEmitDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;").WithWarningAsError(false));
}
[Fact]
public void UnusedUsingInteractive()
{
var tree = Parse("using System;", options: TestOptions.Script);
var comp = CSharpCompilation.CreateScriptCompilation("sub1", tree, new[] { MscorlibRef_v4_0_30316_17626 });
comp.VerifyDiagnostics();
}
[Fact]
public void UnusedUsingScript()
{
var tree = Parse("using System;", options: TestOptions.Script);
var comp = CreateCompilationWithMscorlib45(new[] { tree });
comp.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System;
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System;"));
}
[Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")]
public void IncorrectUnusedUsingWhenAttributeOnParameter_01()
{
var source1 =
@"using System.Runtime.InteropServices;
partial class Program
{
partial void M([Out] [In] ref int x) { }
}";
var source2 =
@"partial class Program
{
partial void M(ref int x);
}";
var comp = CreateCompilation(new[] { source1, source2 });
var tree = comp.SyntaxTrees[0];
//comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug
var model = comp.GetSemanticModel(tree);
// There should be no diagnostics.
model.GetDiagnostics().Verify(
//// (1,1): hidden CS8019: Unnecessary using directive.
//// using System.Runtime.InteropServices;
//Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1)
);
}
[Fact, WorkItem(18348, "https://github.com/dotnet/roslyn/issues/18348")]
public void IncorrectUnusedUsingWhenAttributeOnParameter_02()
{
var source1 =
@"using System.Runtime.InteropServices;
partial class Program
{
partial void M([Out] [In] ref int x);
}";
var source2 =
@"partial class Program
{
partial void M(ref int x) { }
}";
var comp = CreateCompilation(new[] { source1, source2 });
var tree = comp.SyntaxTrees[0];
//comp.VerifyDiagnostics(); // doing this first hides the symptoms of the bug
var model = comp.GetSemanticModel(tree);
// There should be no diagnostics.
model.GetDiagnostics().Verify(
//// (1,1): hidden CS8019: Unnecessary using directive.
//// using System.Runtime.InteropServices;
//Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Runtime.InteropServices;").WithLocation(1, 1)
);
}
[Fact, WorkItem(2773, "https://github.com/dotnet/roslyn/issues/2773")]
public void UsageInDocComment()
{
var source = @"using X;
/// <summary/>
public class Program
{
/// <summary>
/// <see cref=""Q""/>
/// </summary>
static void Main(string[] args)
{
}
}
namespace X
{
/// <summary/>
public class Q { }
}
";
foreach (DocumentationMode documentationMode in Enum.GetValues(typeof(DocumentationMode)))
{
var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithDocumentationMode(documentationMode));
compilation.VerifyDiagnostics();
}
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Compilers/CSharp/Test/Symbol/Compilation/SymbolSearchTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SymbolSearchTests : CSharpTestBase
{
[Fact]
public void TestSymbolFilterNone()
{
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName(n => true, SymbolFilter.None);
});
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName(n => true, SymbolFilter.None);
});
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName("", SymbolFilter.None);
});
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName("", SymbolFilter.None);
});
}
[Fact]
public void TestPredicateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName(predicate: null);
});
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName(predicate: null);
});
}
[Fact]
public void TestNameNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName(name: null);
});
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName(name: null);
});
}
[Fact]
public void TestMergedNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: true, count: 0);
}
[Fact]
public void TestSourceNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: true, count: 0);
}
[Fact]
public void TestClassInMergedNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: true, count: 0);
}
[Fact]
public void TestClassInSourceNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: true, count: 0);
}
[Fact]
public void TestMembers()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: false, count: 0);
}
[Fact]
public void TestPartialSearch()
{
var compilation = GetTestCompilation();
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 4);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: false, count: 4);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: true, count: 8);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: false, count: 1);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: true, count: 5);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: false, count: 5);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 9);
Test(compilation, n => n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 2);
}
[WorkItem(876191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876191")]
[Fact]
public void TestExplicitInterfaceSearch()
{
const string source = @"
interface I
{
void M();
}
class Explicit : I
{
void I.M() { }
}
class Implicit : I
{
public void M() { }
}
";
var compilation = CreateCompilation(new[] { source });
Test(compilation, n => n.IndexOf("M", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 3);
}
private static CSharpCompilation GetTestCompilation()
{
const string source = @"
namespace System
{
public class Test { }
}
namespace MyNamespace
{
public class Test1 { }
}
public class MyClass
{
private int myField;
internal int MyProperty { get; set; }
void MyMethod() { }
public event EventHandler MyEvent;
delegate string MyDelegate(int i);
}
struct MyStruct
{
}
interface MyInterface
{
}
enum Enum
{
EnumValue
}
";
return CreateCompilation(source: new string[] { source });
}
private static void TestNameAndPredicate(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count)
{
Test(compilation, name, includeNamespace, includeType, includeMember, count);
Test(compilation, n => n == name, includeNamespace, includeType, includeMember, count);
}
private static void Test(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count)
{
SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember);
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter));
Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count());
}
private static void Test(CSharpCompilation compilation, Func<string, bool> predicate, bool includeNamespace, bool includeType, bool includeMember, int count)
{
SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember);
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter));
Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count());
}
private static SymbolFilter ComputeFilter(bool includeNamespace, bool includeType, bool includeMember)
{
var filter = SymbolFilter.None;
filter = includeNamespace ? (filter | SymbolFilter.Namespace) : filter;
filter = includeType ? (filter | SymbolFilter.Type) : filter;
filter = includeMember ? (filter | SymbolFilter.Member) : filter;
return filter;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class SymbolSearchTests : CSharpTestBase
{
[Fact]
public void TestSymbolFilterNone()
{
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName(n => true, SymbolFilter.None);
});
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName(n => true, SymbolFilter.None);
});
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName("", SymbolFilter.None);
});
Assert.Throws<ArgumentException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName("", SymbolFilter.None);
});
}
[Fact]
public void TestPredicateNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName(predicate: null);
});
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName(predicate: null);
});
}
[Fact]
public void TestNameNull()
{
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.ContainsSymbolsWithName(name: null);
});
Assert.Throws<ArgumentNullException>(() =>
{
var compilation = GetTestCompilation();
compilation.GetSymbolsWithName(name: null);
});
}
[Fact]
public void TestMergedNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "System", includeNamespace: false, includeType: true, includeMember: true, count: 0);
}
[Fact]
public void TestSourceNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "MyNamespace", includeNamespace: false, includeType: true, includeMember: true, count: 0);
}
[Fact]
public void TestClassInMergedNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "Test", includeNamespace: true, includeType: false, includeMember: true, count: 0);
}
[Fact]
public void TestClassInSourceNamespace()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: false, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "Test1", includeNamespace: false, includeType: false, includeMember: true, count: 0);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "Test1", includeNamespace: true, includeType: false, includeMember: true, count: 0);
}
[Fact]
public void TestMembers()
{
var compilation = GetTestCompilation();
TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: true, count: 1);
TestNameAndPredicate(compilation, "myField", includeNamespace: false, includeType: true, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: false, includeMember: false, count: 0);
TestNameAndPredicate(compilation, "myField", includeNamespace: true, includeType: true, includeMember: false, count: 0);
}
[Fact]
public void TestPartialSearch()
{
var compilation = GetTestCompilation();
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 4);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: false, count: 4);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: true, includeMember: true, count: 8);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: false, count: 1);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: false, includeMember: true, count: 5);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: false, count: 5);
Test(compilation, n => n.IndexOf("my", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 9);
Test(compilation, n => n.IndexOf("enum", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: true, includeType: true, includeMember: true, count: 2);
}
[WorkItem(876191, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/876191")]
[Fact]
public void TestExplicitInterfaceSearch()
{
const string source = @"
interface I
{
void M();
}
class Explicit : I
{
void I.M() { }
}
class Implicit : I
{
public void M() { }
}
";
var compilation = CreateCompilation(new[] { source });
Test(compilation, n => n.IndexOf("M", StringComparison.OrdinalIgnoreCase) >= 0, includeNamespace: false, includeType: false, includeMember: true, count: 3);
}
private static CSharpCompilation GetTestCompilation()
{
const string source = @"
namespace System
{
public class Test { }
}
namespace MyNamespace
{
public class Test1 { }
}
public class MyClass
{
private int myField;
internal int MyProperty { get; set; }
void MyMethod() { }
public event EventHandler MyEvent;
delegate string MyDelegate(int i);
}
struct MyStruct
{
}
interface MyInterface
{
}
enum Enum
{
EnumValue
}
";
return CreateCompilation(source: new string[] { source });
}
private static void TestNameAndPredicate(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count)
{
Test(compilation, name, includeNamespace, includeType, includeMember, count);
Test(compilation, n => n == name, includeNamespace, includeType, includeMember, count);
}
private static void Test(CSharpCompilation compilation, string name, bool includeNamespace, bool includeType, bool includeMember, int count)
{
SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember);
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(name, filter));
Assert.Equal(count, compilation.GetSymbolsWithName(name, filter).Count());
}
private static void Test(CSharpCompilation compilation, Func<string, bool> predicate, bool includeNamespace, bool includeType, bool includeMember, int count)
{
SymbolFilter filter = ComputeFilter(includeNamespace, includeType, includeMember);
Assert.Equal(count > 0, compilation.ContainsSymbolsWithName(predicate, filter));
Assert.Equal(count, compilation.GetSymbolsWithName(predicate, filter).Count());
}
private static SymbolFilter ComputeFilter(bool includeNamespace, bool includeType, bool includeMember)
{
var filter = SymbolFilter.None;
filter = includeNamespace ? (filter | SymbolFilter.Namespace) : filter;
filter = includeType ? (filter | SymbolFilter.Type) : filter;
filter = includeMember ? (filter | SymbolFilter.Member) : filter;
return filter;
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/EditorFeatures/VisualBasicTest/Recommendations/Declarations/StaticKeywordRecommenderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class StaticKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Static")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticInLambdaTest()
VerifyRecommendationsContain(<MethodBody>
Dim x = Sub()
|
End Sub</MethodBody>, "Static")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "Static")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticNotInsideSingleLineLambdaTest()
VerifyRecommendationsMissing(<MethodBody>
Dim x = Sub() |
</MethodBody>, "Static")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Declarations
Public Class StaticKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticInMethodBodyTest()
VerifyRecommendationsContain(<MethodBody>|</MethodBody>, "Static")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticInLambdaTest()
VerifyRecommendationsContain(<MethodBody>
Dim x = Sub()
|
End Sub</MethodBody>, "Static")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticAfterStatementTest()
VerifyRecommendationsContain(<MethodBody>
Dim x
|</MethodBody>, "Static")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub StaticNotInsideSingleLineLambdaTest()
VerifyRecommendationsMissing(<MethodBody>
Dim x = Sub() |
</MethodBody>, "Static")
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/VisualStudio/Core/Test/Venus/VisualBasicContainedLanguageSupportTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
Public Class VisualBasicContainedLanguageCodeSupportTests
Inherits AbstractContainedLanguageCodeSupportTests
#Region "IsValid Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_1()
AssertValidId("field")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_Escaped()
AssertValidId("[field]")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_EscapedKeyword()
AssertValidId("[Class]")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_ContainsNumbers()
AssertValidId("abc123")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_Keyword()
AssertNotValidId("Class")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_StartsWithNumber()
AssertNotValidId("123abc")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_Punctuation()
AssertNotValidId("abc.abc")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_TypeChar()
AssertValidId("abc$")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_TypeCharInMiddle()
AssertNotValidId("abc$abc")
End Sub
#End Region
#Region "GetBaseClassName Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_NonexistingClass()
Dim code As String = <text>Class c
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.False(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "A",
CancellationToken.None, baseClassName))
Assert.Null(baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_DerivedFromObject()
Dim code As String = <text>Class C
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C",
CancellationToken.None, baseClassName))
Assert.Equal("Object", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_DerivedFromFrameworkType()
Dim code As String = <text>
Imports System
Class C
Inherits Exception
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C",
CancellationToken.None, baseClassName))
Assert.Equal("System.Exception", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_DerivedFromUserDefinedType()
Dim code As String = <text>
Class B
End Class
Class C
Inherits B
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C",
CancellationToken.None, baseClassName))
Assert.Equal("B", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_FullyQualifiedNames()
Dim code As String = <text>
Namespace N
Class B
End Class
Class C
Inherits B
End Class
End Namespace</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C",
CancellationToken.None, baseClassName))
Assert.Equal("N.B", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_MinimallyQualifiedNames()
Dim code As String = <text>
Namespace N
Class B
End Class
Class C
Inherits B
End Class
End Namespace</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C",
CancellationToken.None, baseClassName))
Assert.Equal("N.B", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_EscapedKeyword()
Dim code As String = <text>
Class [Class]
End Class
Class Derived
Inherits [Class]
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "Derived",
CancellationToken.None, baseClassName))
Assert.Equal("[Class]", baseClassName)
End Using
End Sub
#End Region
#Region "CreateUniqueEventName Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_ButtonClick()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionWithEventHandler()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionWithOtherMembers()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Public Property Button1_Click As String
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionFromPartialClass()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
Public Partial Class _Default
Public Property Button1_Click As String
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionFromBaseClass()
Dim code As String = <text>
Public Partial Class _Default
Inherits MyBaseClass
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
Public Class MyBaseClass
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
#End Region
#Region "GetCompatibleEventHandlers"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_EventDoesntExist()
Dim code As String = <text>
Imports System
Public Class Button
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Assert.Throws(Of InvalidOperationException)(
Sub()
ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
cancellationToken:=Nothing)
End Sub)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_ObjTypeNameIsWrong()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Assert.Throws(Of InvalidOperationException)(
Sub()
ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="CheckBox",
nameOfEvent:="Click",
cancellationToken:=Nothing)
End Sub)
End Using
End Sub
' To Do: Investigate - this feels wrong. when Handles Clause exists
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_MatchExists()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal(1, eventHandlers.Count())
Assert.Equal("Page_Load", eventHandlers.Single().Item1)
Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlers.Single().Item2)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_MatchesExist()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal(2, eventHandlers.Count())
' It has to be page_load and button click, but are they always ordered in the same way?
End Using
End Sub
' add tests for CompatibleSignatureToDelegate (#params, return type)
#End Region
#Region "GetEventHandlerMemberId"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetEventHandlerMemberId_HandlerExists()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerId)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetEventHandlerMemberId_CantFindHandler()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
cancellationToken:=Nothing)
Assert.Equal(Nothing, eventHandlerId)
End Using
End Sub
#End Region
#Region "EnsureEventHandler"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestEnsureEventHandler_HandlerExists()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument:=document,
targetDocument:=document,
className:="_Default",
objectName:="Button1",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
itemidInsertionPoint:=0,
useHandlesClause:=True,
additionalFormattingRule:=LineAdjustmentFormattingRule.Instance,
cancellationToken:=Nothing)
' Since a valid handler exists, item2 and item3 of the tuple returned must be nothing
Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1)
Assert.Equal(Nothing, eventHandlerIdTextPosition.Item2)
Assert.Equal(New TextSpan(), eventHandlerIdTextPosition.Item3)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestEnsureEventHandler_GenerateNewHandler()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
End Class</text>.NormalizedValue
Dim generatedCode As String = <text>
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub</text>.NormalizedValue
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument:=document,
targetDocument:=document,
className:="_Default",
objectName:="Button1",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
itemidInsertionPoint:=0,
useHandlesClause:=True,
additionalFormattingRule:=LineAdjustmentFormattingRule.Instance,
cancellationToken:=Nothing)
Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1)
TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language)
Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
<WorkItem(850035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850035")>
Public Sub TestEnsureEventHandler_WithHandlesAndNullObjectName()
Dim code As String = "
Imports System
Namespace System.Web.UI
Public Class Page
Public Event Load as EventHandler
End Class
End Namespace
Public Class _Default
Inherits System.Web.UI.Page
End Class"
Dim generatedCode As String = "
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub"
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument:=document,
targetDocument:=document,
className:="_Default",
objectName:=Nothing,
objectTypeName:="System.Web.UI.Page",
nameOfEvent:="Load",
eventHandlerName:="Page_Load",
itemidInsertionPoint:=0,
useHandlesClause:=True,
additionalFormattingRule:=LineAdjustmentFormattingRule.Instance,
cancellationToken:=Nothing)
Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1)
TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language)
Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3)
End Using
End Sub
#End Region
#Region "GetMemberNavigationPoint"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMemberNavigationPoint()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
' Expect the cursor to be inside the method body of Button1_Click, line 14 column 8
Dim expectedSpan As New Microsoft.VisualStudio.TextManager.Interop.TextSpan() With
{
.iStartLine = 14,
.iStartIndex = 8,
.iEndLine = 14,
.iEndIndex = 8
}
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim targetDocument As Document = Nothing
Dim actualSpan As TextSpan = Nothing
If Not ContainedLanguageCodeSupport.TryGetMemberNavigationPoint(
thisDocument:=document,
className:="_Default",
uniqueMemberID:="Button1_Click(Object,System.EventArgs)",
textSpan:=actualSpan,
targetDocument:=targetDocument,
cancellationToken:=Nothing) Then
Assert.True(False, "should have succeeded")
End If
Assert.Equal(expectedSpan, actualSpan)
End Using
End Sub
#End Region
#Region "GetMembers"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlersWrongParamType()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As Object)
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(0, members.Count())
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlersWrongParamCount()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object)
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(0, members.Count())
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlersWrongReturnType()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Function Page_Load(sender As Object, e As EventArgs) As Integer
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(0, members.Count())
End Using
End Sub
' To Do: Investigate, this returns the method even if handles is missing. that ok?
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlers()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(1, members.Count())
Dim userFunction = members.First()
Assert.Equal("Page_Load", userFunction.Item1)
Assert.Equal("Page_Load(Object,System.EventArgs)", userFunction.Item2)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_UserFunctions()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Test(x as String)
End Sub
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS,
cancellationToken:=Nothing)
Assert.Equal(1, members.Count())
Dim userFunction = members.First()
Assert.Equal("Test", userFunction.Item1)
Assert.Equal("Test(String)", userFunction.Item2)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_Events()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="Button",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS,
cancellationToken:=Nothing)
Assert.Equal(1, members.Count())
Dim userFunction = members.First()
Assert.Equal("Click", userFunction.Item1)
Assert.Equal("Click(EVENT)", userFunction.Item2)
End Using
End Sub
#End Region
#Region "OnRenamed (TryRenameElement)"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_ResolvableMembers()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER,
oldFullyQualifiedName:="_Default.Page_Load",
newFullyQualifiedName:="_Default.Page_Load1",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
' To Do: Who tests the fully qualified names and their absence?
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_UnresolvableMembers()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER,
oldFullyQualifiedName:="_Default.Fictional",
newFullyQualifiedName:="_Default.Fictional1",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.False(renameSucceeded)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_ResolvableClass()
Dim code As String = <text>Public Partial Class Goo
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASS,
oldFullyQualifiedName:="Goo",
newFullyQualifiedName:="Bar",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_ResolvableNamespace()
Dim code As String = <text>Namespace Goo
End Namespace</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_NAMESPACE,
oldFullyQualifiedName:="Goo",
newFullyQualifiedName:="Bar",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_Button()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER,
oldFullyQualifiedName:="_Default.button",
newFullyQualifiedName:="_Default.button1",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
#End Region
' TODO: Does Dev10 cover more here, like conflicts with existing members?
Protected Overrides ReadOnly Property DefaultCode As String
Get
Return <text>
Class C
End Class
</text>.Value
End Get
End Property
Protected Overrides ReadOnly Property Language As String
Get
Return Microsoft.CodeAnalysis.LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.Utilities
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Venus
Imports Microsoft.VisualStudio.TextManager.Interop
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Imports TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.Venus
Public Class VisualBasicContainedLanguageCodeSupportTests
Inherits AbstractContainedLanguageCodeSupportTests
#Region "IsValid Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_1()
AssertValidId("field")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_Escaped()
AssertValidId("[field]")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_EscapedKeyword()
AssertValidId("[Class]")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_ContainsNumbers()
AssertValidId("abc123")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_Keyword()
AssertNotValidId("Class")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_StartsWithNumber()
AssertNotValidId("123abc")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_Punctuation()
AssertNotValidId("abc.abc")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_TypeChar()
AssertValidId("abc$")
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestIsValidId_TypeCharInMiddle()
AssertNotValidId("abc$abc")
End Sub
#End Region
#Region "GetBaseClassName Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_NonexistingClass()
Dim code As String = <text>Class c
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.False(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "A",
CancellationToken.None, baseClassName))
Assert.Null(baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_DerivedFromObject()
Dim code As String = <text>Class C
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C",
CancellationToken.None, baseClassName))
Assert.Equal("Object", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_DerivedFromFrameworkType()
Dim code As String = <text>
Imports System
Class C
Inherits Exception
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C",
CancellationToken.None, baseClassName))
Assert.Equal("System.Exception", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_DerivedFromUserDefinedType()
Dim code As String = <text>
Class B
End Class
Class C
Inherits B
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "C",
CancellationToken.None, baseClassName))
Assert.Equal("B", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_FullyQualifiedNames()
Dim code As String = <text>
Namespace N
Class B
End Class
Class C
Inherits B
End Class
End Namespace</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C",
CancellationToken.None, baseClassName))
Assert.Equal("N.B", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_MinimallyQualifiedNames()
Dim code As String = <text>
Namespace N
Class B
End Class
Class C
Inherits B
End Class
End Namespace</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "N.C",
CancellationToken.None, baseClassName))
Assert.Equal("N.B", baseClassName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetBaseClassName_EscapedKeyword()
Dim code As String = <text>
Class [Class]
End Class
Class Derived
Inherits [Class]
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim baseClassName As String = Nothing
Assert.True(ContainedLanguageCodeSupport.TryGetBaseClassName(document, "Derived",
CancellationToken.None, baseClassName))
Assert.Equal("[Class]", baseClassName)
End Using
End Sub
#End Region
#Region "CreateUniqueEventName Tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_ButtonClick()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionWithEventHandler()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionWithOtherMembers()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Public Property Button1_Click As String
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionFromPartialClass()
Dim code As String = <text>
Public Partial Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
Public Partial Class _Default
Public Property Button1_Click As String
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestCreateUniqueEventName_NameCollisionFromBaseClass()
Dim code As String = <text>
Public Partial Class _Default
Inherits MyBaseClass
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class
Public Class MyBaseClass
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventName = ContainedLanguageCodeSupport.CreateUniqueEventName(
document:=document,
className:="_Default",
objectName:="Button1",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click1", eventName)
End Using
End Sub
#End Region
#Region "GetCompatibleEventHandlers"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_EventDoesntExist()
Dim code As String = <text>
Imports System
Public Class Button
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Assert.Throws(Of InvalidOperationException)(
Sub()
ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
cancellationToken:=Nothing)
End Sub)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_ObjTypeNameIsWrong()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Assert.Throws(Of InvalidOperationException)(
Sub()
ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="CheckBox",
nameOfEvent:="Click",
cancellationToken:=Nothing)
End Sub)
End Using
End Sub
' To Do: Investigate - this feels wrong. when Handles Clause exists
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_MatchExists()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal(1, eventHandlers.Count())
Assert.Equal("Page_Load", eventHandlers.Single().Item1)
Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlers.Single().Item2)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetCompatibleEventHandlers_MatchesExist()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlers = ContainedLanguageCodeSupport.GetCompatibleEventHandlers(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
cancellationToken:=Nothing)
Assert.Equal(2, eventHandlers.Count())
' It has to be page_load and button click, but are they always ordered in the same way?
End Using
End Sub
' add tests for CompatibleSignatureToDelegate (#params, return type)
#End Region
#Region "GetEventHandlerMemberId"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetEventHandlerMemberId_HandlerExists()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
cancellationToken:=Nothing)
Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerId)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetEventHandlerMemberId_CantFindHandler()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerId = ContainedLanguageCodeSupport.GetEventHandlerMemberId(
document:=document,
className:="_Default",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
cancellationToken:=Nothing)
Assert.Equal(Nothing, eventHandlerId)
End Using
End Sub
#End Region
#Region "EnsureEventHandler"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestEnsureEventHandler_HandlerExists()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument:=document,
targetDocument:=document,
className:="_Default",
objectName:="Button1",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
itemidInsertionPoint:=0,
useHandlesClause:=True,
additionalFormattingRule:=LineAdjustmentFormattingRule.Instance,
cancellationToken:=Nothing)
' Since a valid handler exists, item2 and item3 of the tuple returned must be nothing
Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1)
Assert.Equal(Nothing, eventHandlerIdTextPosition.Item2)
Assert.Equal(New TextSpan(), eventHandlerIdTextPosition.Item3)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestEnsureEventHandler_GenerateNewHandler()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs)
End Sub
End Class</text>.NormalizedValue
Dim generatedCode As String = <text>
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub</text>.NormalizedValue
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument:=document,
targetDocument:=document,
className:="_Default",
objectName:="Button1",
objectTypeName:="Button",
nameOfEvent:="Click",
eventHandlerName:="Button1_Click",
itemidInsertionPoint:=0,
useHandlesClause:=True,
additionalFormattingRule:=LineAdjustmentFormattingRule.Instance,
cancellationToken:=Nothing)
Assert.Equal("Button1_Click(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1)
TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language)
Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
<WorkItem(850035, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/850035")>
Public Sub TestEnsureEventHandler_WithHandlesAndNullObjectName()
Dim code As String = "
Imports System
Namespace System.Web.UI
Public Class Page
Public Event Load as EventHandler
End Class
End Namespace
Public Class _Default
Inherits System.Web.UI.Page
End Class"
Dim generatedCode As String = "
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub"
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim eventHandlerIdTextPosition = ContainedLanguageCodeSupport.EnsureEventHandler(
thisDocument:=document,
targetDocument:=document,
className:="_Default",
objectName:=Nothing,
objectTypeName:="System.Web.UI.Page",
nameOfEvent:="Load",
eventHandlerName:="Page_Load",
itemidInsertionPoint:=0,
useHandlesClause:=True,
additionalFormattingRule:=LineAdjustmentFormattingRule.Instance,
cancellationToken:=Nothing)
Assert.Equal("Page_Load(Object,System.EventArgs)", eventHandlerIdTextPosition.Item1)
TokenUtilities.AssertTokensEqual(generatedCode, eventHandlerIdTextPosition.Item2, Language)
Assert.Equal(New TextSpan With {.iStartLine = 12, .iEndLine = 12}, eventHandlerIdTextPosition.Item3)
End Using
End Sub
#End Region
#Region "GetMemberNavigationPoint"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMemberNavigationPoint()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
' Expect the cursor to be inside the method body of Button1_Click, line 14 column 8
Dim expectedSpan As New Microsoft.VisualStudio.TextManager.Interop.TextSpan() With
{
.iStartLine = 14,
.iStartIndex = 8,
.iEndLine = 14,
.iEndIndex = 8
}
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim targetDocument As Document = Nothing
Dim actualSpan As TextSpan = Nothing
If Not ContainedLanguageCodeSupport.TryGetMemberNavigationPoint(
thisDocument:=document,
className:="_Default",
uniqueMemberID:="Button1_Click(Object,System.EventArgs)",
textSpan:=actualSpan,
targetDocument:=targetDocument,
cancellationToken:=Nothing) Then
Assert.True(False, "should have succeeded")
End If
Assert.Equal(expectedSpan, actualSpan)
End Using
End Sub
#End Region
#Region "GetMembers"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlersWrongParamType()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As Object)
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(0, members.Count())
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlersWrongParamCount()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object)
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(0, members.Count())
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlersWrongReturnType()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Function Page_Load(sender As Object, e As EventArgs) As Integer
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(0, members.Count())
End Using
End Sub
' To Do: Investigate, this returns the method even if handles is missing. that ok?
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_EventHandlers()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENT_HANDLERS,
cancellationToken:=Nothing)
Assert.Equal(1, members.Count())
Dim userFunction = members.First()
Assert.Equal("Page_Load", userFunction.Item1)
Assert.Equal("Page_Load(Object,System.EventArgs)", userFunction.Item2)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_UserFunctions()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Test(x as String)
End Sub
End Class
</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="_Default",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_USER_FUNCTIONS,
cancellationToken:=Nothing)
Assert.Equal(1, members.Count())
Dim userFunction = members.First()
Assert.Equal("Test", userFunction.Item1)
Assert.Equal("Test(String)", userFunction.Item2)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestGetMembers_Events()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim members = ContainedLanguageCodeSupport.GetMembers(
document:=document,
className:="Button",
codeMemberType:=CODEMEMBERTYPE.CODEMEMBERTYPE_EVENTS,
cancellationToken:=Nothing)
Assert.Equal(1, members.Count())
Dim userFunction = members.First()
Assert.Equal("Click", userFunction.Item1)
Assert.Equal("Click(EVENT)", userFunction.Item2)
End Using
End Sub
#End Region
#Region "OnRenamed (TryRenameElement)"
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_ResolvableMembers()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER,
oldFullyQualifiedName:="_Default.Page_Load",
newFullyQualifiedName:="_Default.Page_Load1",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
' To Do: Who tests the fully qualified names and their absence?
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_UnresolvableMembers()
Dim code As String = <text>
Imports System
Public Partial Class _Default
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER,
oldFullyQualifiedName:="_Default.Fictional",
newFullyQualifiedName:="_Default.Fictional1",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.False(renameSucceeded)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_ResolvableClass()
Dim code As String = <text>Public Partial Class Goo
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASS,
oldFullyQualifiedName:="Goo",
newFullyQualifiedName:="Bar",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_ResolvableNamespace()
Dim code As String = <text>Namespace Goo
End Namespace</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_NAMESPACE,
oldFullyQualifiedName:="Goo",
newFullyQualifiedName:="Bar",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
<WpfFact, Trait(Traits.Feature, Traits.Features.Venus)>
Public Sub TestTryRenameElement_Button()
Dim code As String = <text>
Imports System
Public Class Button
Public Event Click As EventHandler
End Class
Public Class _Default
Private button As Button
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
End Sub
End Class</text>.Value
Using workspace = GetWorkspace(code)
Dim document = GetDocument(workspace)
Dim renameSucceeded = ContainedLanguageCodeSupport.TryRenameElement(
document:=document,
clrt:=ContainedLanguageRenameType.CLRT_CLASSMEMBER,
oldFullyQualifiedName:="_Default.button",
newFullyQualifiedName:="_Default.button1",
refactorNotifyServices:=SpecializedCollections.EmptyEnumerable(Of IRefactorNotifyService),
cancellationToken:=Nothing)
Assert.True(renameSucceeded)
End Using
End Sub
#End Region
' TODO: Does Dev10 cover more here, like conflicts with existing members?
Protected Overrides ReadOnly Property DefaultCode As String
Get
Return <text>
Class C
End Class
</text>.Value
End Get
End Property
Protected Overrides ReadOnly Property Language As String
Get
Return Microsoft.CodeAnalysis.LanguageNames.VisualBasic
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/VisualStudio/Core/Test/DebuggerIntelliSense/CSharpDebuggerIntellisenseTests.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 Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
<[UseExportProvider]>
Public Class CSharpDebuggerIntellisenseTests
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacter() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacterInImmediateWindow() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalsInBlockAfterInstructionPointer() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
int x = 3;
string bar = "goo";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("x")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("x")
state.SendBackspace()
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionAfterReturn() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
int x = 3;
string bar = "goo";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
state.SendReturn()
Assert.Equal("", state.GetCurrentViewLineText())
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ExecutedUnexecutedLocals() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("goo")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("goo")
state.SendTab()
state.SendTypeChars(".ToS")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("ToString")
For i As Integer = 0 To 7
state.SendBackspace()
Next
Await state.AssertNoCompletionSession()
state.SendTypeChars("green")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("green")
state.SendTab()
state.SendTypeChars(".ToS")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("ToString")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals1() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
[|int variable1 = 0;|]
}
Console.Write(0);
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainAll("variable1", "variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals2() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
[|}|]
Console.Write(0);
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainAll("variable1", "variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals3() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
[|Console.Write(0);|]
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals4() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
[|int variable2 = 0;|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals5() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
int variable2 = 0;
[|}|]
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals6() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
int variable2 = 0;
}
[|}|]</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsDoNotContainAny("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInParameterizedConstructor() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("new string(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInMethodCall() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void something(string z, int b)
{
}
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("something(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInGenericMethodCall() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void something<T>(<T> z, int b)
{
return z
}
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("something<int>(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function InstructionPointerInForeach() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
int OOO = 3;
foreach (var z in "goo")
{
[|var q = 1;|]
}
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
Await state.VerifyCompletionAndDotAfter("q")
Await state.VerifyCompletionAndDotAfter("OOO")
End Using
End Function
<WorkItem(531165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531165")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ClassDesigner1() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static int STATICINT;
static void Main(string[] args)
{
}
[| |] public void M1()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("STATICI")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("STATICINT")
End Using
End Function
<WorkItem(531167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531167")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ClassDesigner2() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
}
[| |] void M1()
{
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("1")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(1124544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124544")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionUsesContextBufferPositions() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacterInLinkedFileContext() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs">
{
static void Main(string[] args)
[|{|]
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.TextView.TextBuffer.Insert(0, "123123123123123123123123123 + ")
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText())
state.SendTab()
Assert.Contains("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TypeNumberAtStartOfViewDoesNotCrash() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("4")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function BuilderSettingRetainedBetweenComputations_Watch() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=False)
state.SendTypeChars("args")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("args", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
Assert.True(state.HasSuggestedItem())
state.SendToggleCompletionMode()
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function BuilderSettingRetainedBetweenComputations_Watch_Immediate() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=True)
state.SendTypeChars("args")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("args", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
Assert.True(state.HasSuggestedItem())
state.SendToggleCompletionMode()
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
End Using
End Function
<WorkItem(1163608, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1163608")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TestItemDescription() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("args")
Dim description = Await state.GetSelectedItemDescriptionAsync()
Assert.Contains("args", description.Text)
state.SendTab()
Assert.Contains("args", state.GetCurrentViewLineText())
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 Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.DebuggerIntelliSense
<[UseExportProvider]>
Public Class CSharpDebuggerIntellisenseTests
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacter() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacterInImmediateWindow() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function LocalsInBlockAfterInstructionPointer() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
int x = 3;
string bar = "goo";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("x")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("x")
state.SendBackspace()
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionAfterReturn() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
int x = 3;
string bar = "goo";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
state.SendReturn()
Assert.Equal("", state.GetCurrentViewLineText())
state.SendTypeChars("bar")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("bar")
state.SendTab()
Assert.Equal("bar", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ExecutedUnexecutedLocals() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("goo")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("goo")
state.SendTab()
state.SendTypeChars(".ToS")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("ToString")
For i As Integer = 0 To 7
state.SendBackspace()
Next
Await state.AssertNoCompletionSession()
state.SendTypeChars("green")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("green")
state.SendTab()
state.SendTypeChars(".ToS")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSelectedCompletionItem("ToString")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals1() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
[|int variable1 = 0;|]
}
Console.Write(0);
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainAll("variable1", "variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals2() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
[|}|]
Console.Write(0);
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsContainAll("variable1", "variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals3() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
[|Console.Write(0);|]
int variable2 = 0;
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals4() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
[|int variable2 = 0;|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals5() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
int variable2 = 0;
[|}|]
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsContainAll("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function Locals6() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main()
{
{
int variable1 = 0;
}
Console.Write(0);
int variable2 = 0;
}
[|}|]</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("variable")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("variable1")
Await state.AssertCompletionItemsDoNotContainAny("variable2")
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInParameterizedConstructor() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("new string(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInMethodCall() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void something(string z, int b)
{
}
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("something(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function SignatureHelpInGenericMethodCall() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void something<T>(<T> z, int b)
{
return z
}
static void Main(string[] args)
{
string goo = "green";
[|string bar = "goo";|]
string green = "yellow";
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("something<int>(")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertSignatureHelpSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function InstructionPointerInForeach() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
int OOO = 3;
foreach (var z in "goo")
{
[|var q = 1;|]
}
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
Await state.VerifyCompletionAndDotAfter("q")
Await state.VerifyCompletionAndDotAfter("OOO")
End Using
End Function
<WorkItem(531165, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531165")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ClassDesigner1() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static int STATICINT;
static void Main(string[] args)
{
}
[| |] public void M1()
{
throw new System.NotImplementedException();
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("STATICI")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionItemsDoNotContainAny("STATICINT")
End Using
End Function
<WorkItem(531167, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531167")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function ClassDesigner2() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
{
}
[| |] void M1()
{
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, False)
state.SendTypeChars("1")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertNoCompletionSession()
End Using
End Function
<WorkItem(1124544, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1124544")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionUsesContextBufferPositions() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.
(1,3): error CS1001: Identifier expected
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
e.InnerException
{"Exception of type 'System.Exception' was thrown."}
Data: {System.Collections.ListDictionaryInternal}
HResult: -2146233088
HelpLink: null
InnerException: null
Message: "Exception of type 'System.Exception' was thrown."
Source: null
StackTrace: null
TargetSite: null
$$</Document>
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("arg", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
state.SendTab()
Assert.Equal("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function CompletionOnTypeCharacterInLinkedFileContext() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document IsLinkFile="true" LinkAssemblyName="CSProj" LinkFilePath="C.cs"/>
</Project>
<Project Language="C#" CommonReferences="true" AssemblyName="CSProj">
<Document FilePath="C.cs">
{
static void Main(string[] args)
[|{|]
}
}
</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.TextView.TextBuffer.Insert(0, "123123123123123123123123123 + ")
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("123123123123123123123123123 + arg", state.GetCurrentViewLineText())
state.SendTab()
Assert.Contains("args", state.GetCurrentViewLineText())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TypeNumberAtStartOfViewDoesNotCrash() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendInvokeCompletionList()
Await state.AssertCompletionSession()
state.SendTypeChars("4")
Await state.AssertNoCompletionSession()
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function BuilderSettingRetainedBetweenComputations_Watch() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=False)
state.SendTypeChars("args")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("args", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
Assert.True(state.HasSuggestedItem())
state.SendToggleCompletionMode()
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
End Using
End Function
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function BuilderSettingRetainedBetweenComputations_Watch_Immediate() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, isImmediateWindow:=True)
state.SendTypeChars("args")
Await state.WaitForAsynchronousOperationsAsync()
Assert.Equal("args", state.GetCurrentViewLineText())
Await state.AssertCompletionSession()
Assert.True(state.HasSuggestedItem())
state.SendToggleCompletionMode()
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
state.SendTypeChars(".")
Await state.WaitForAsynchronousOperationsAsync()
Assert.False(state.HasSuggestedItem())
End Using
End Function
<WorkItem(1163608, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1163608")>
<WpfFact, Trait(Traits.Feature, Traits.Features.DebuggingIntelliSense)>
Public Async Function TestItemDescription() As Task
Dim text = <Workspace>
<Project Language="C#" CommonReferences="true">
<Document>class Program
{
static void Main(string[] args)
[|{|]
}
}</Document>
</Project>
</Workspace>
Using state = TestState.CreateCSharpTestState(text, True)
state.SendTypeChars("arg")
Await state.WaitForAsynchronousOperationsAsync()
Await state.AssertCompletionSession()
Await state.AssertSelectedCompletionItem("args")
Dim description = Await state.GetSelectedItemDescriptionAsync()
Assert.Contains("args", description.Text)
state.SendTab()
Assert.Contains("args", state.GetCurrentViewLineText())
End Using
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/EditorFeatures/Test/EditorConfigSettings/Data/CodeStyleSettingsTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using WORKSPACES::Microsoft.CodeAnalysis.Options;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorConfigSettings.Data
{
public class CodeStyleSettingsTest
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void CodeStyleSettingBoolFactory(bool defaultValue)
{
var option = CreateBoolOption(defaultValue);
var editorConfigOptions = new TestAnalyzerConfigOptions();
var visualStudioOptions = new TestOptionSet<bool>(option.DefaultValue);
var setting = CodeStyleSetting.Create(option, description: "TestDesciption", editorConfigOptions, visualStudioOptions, updater: null!, fileName: null!);
Assert.Equal(string.Empty, setting.Category);
Assert.Equal("TestDesciption", setting.Description);
Assert.False(setting.IsDefinedInEditorConfig);
Assert.Equal(typeof(bool), setting.Type);
Assert.Equal(defaultValue, setting.Value);
}
[Theory]
[InlineData(DayOfWeek.Monday)]
[InlineData(DayOfWeek.Friday)]
public static void CodeStyleSettingEnumFactory(DayOfWeek defaultValue)
{
var option = CreateEnumOption(defaultValue);
var editorConfigOptions = new TestAnalyzerConfigOptions();
var visualStudioOptions = new TestOptionSet<DayOfWeek>(option.DefaultValue);
var setting = CodeStyleSetting.Create(option,
description: "TestDesciption",
enumValues: (DayOfWeek[])Enum.GetValues(typeof(DayOfWeek)),
valueDescriptions: Enum.GetNames(typeof(DayOfWeek)),
editorConfigOptions,
visualStudioOptions,
updater: null!,
fileName: null!);
Assert.Equal(string.Empty, setting.Category);
Assert.Equal("TestDesciption", setting.Description);
Assert.False(setting.IsDefinedInEditorConfig);
Assert.Equal(typeof(DayOfWeek), setting.Type);
Assert.Equal(defaultValue, setting.Value);
}
private static Option2<CodeStyleOption2<bool>> CreateBoolOption(bool @default = false)
{
var option = CodeStyleOption2<bool>.Default;
option = (CodeStyleOption2<bool>)((ICodeStyleOption)option).WithValue(@default);
return new Option2<CodeStyleOption2<bool>>(feature: "TestFeature",
name: "TestOption",
defaultValue: option);
}
private static Option2<CodeStyleOption2<T>> CreateEnumOption<T>(T @default)
where T : notnull, Enum
{
var option = CodeStyleOption2<T>.Default;
option = (CodeStyleOption2<T>)((ICodeStyleOption)option).WithValue(@default);
return new Option2<CodeStyleOption2<T>>(feature: "TestFeature",
name: "TestOption",
defaultValue: option);
}
private class TestAnalyzerConfigOptions : AnalyzerConfigOptions
{
private readonly IDictionary<string, string> _dictionary;
public TestAnalyzerConfigOptions((string, string)[]? options = null)
=> _dictionary = options?.ToDictionary(x => x.Item1, x => x.Item2) ?? new Dictionary<string, string>();
public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
=> _dictionary.TryGetValue(key, out value);
}
private class TestOptionSet<T> : OptionSet
{
private readonly object? _value;
public TestOptionSet(CodeStyleOption2<T> value) => _value = value;
public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => this;
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) => Array.Empty<OptionKey>();
private protected override object? GetOptionCore(OptionKey optionKey) => _value;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
extern alias WORKSPACES;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using WORKSPACES::Microsoft.CodeAnalysis.Options;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.EditorConfigSettings.Data
{
public class CodeStyleSettingsTest
{
[Theory]
[InlineData(true)]
[InlineData(false)]
public static void CodeStyleSettingBoolFactory(bool defaultValue)
{
var option = CreateBoolOption(defaultValue);
var editorConfigOptions = new TestAnalyzerConfigOptions();
var visualStudioOptions = new TestOptionSet<bool>(option.DefaultValue);
var setting = CodeStyleSetting.Create(option, description: "TestDesciption", editorConfigOptions, visualStudioOptions, updater: null!, fileName: null!);
Assert.Equal(string.Empty, setting.Category);
Assert.Equal("TestDesciption", setting.Description);
Assert.False(setting.IsDefinedInEditorConfig);
Assert.Equal(typeof(bool), setting.Type);
Assert.Equal(defaultValue, setting.Value);
}
[Theory]
[InlineData(DayOfWeek.Monday)]
[InlineData(DayOfWeek.Friday)]
public static void CodeStyleSettingEnumFactory(DayOfWeek defaultValue)
{
var option = CreateEnumOption(defaultValue);
var editorConfigOptions = new TestAnalyzerConfigOptions();
var visualStudioOptions = new TestOptionSet<DayOfWeek>(option.DefaultValue);
var setting = CodeStyleSetting.Create(option,
description: "TestDesciption",
enumValues: (DayOfWeek[])Enum.GetValues(typeof(DayOfWeek)),
valueDescriptions: Enum.GetNames(typeof(DayOfWeek)),
editorConfigOptions,
visualStudioOptions,
updater: null!,
fileName: null!);
Assert.Equal(string.Empty, setting.Category);
Assert.Equal("TestDesciption", setting.Description);
Assert.False(setting.IsDefinedInEditorConfig);
Assert.Equal(typeof(DayOfWeek), setting.Type);
Assert.Equal(defaultValue, setting.Value);
}
private static Option2<CodeStyleOption2<bool>> CreateBoolOption(bool @default = false)
{
var option = CodeStyleOption2<bool>.Default;
option = (CodeStyleOption2<bool>)((ICodeStyleOption)option).WithValue(@default);
return new Option2<CodeStyleOption2<bool>>(feature: "TestFeature",
name: "TestOption",
defaultValue: option);
}
private static Option2<CodeStyleOption2<T>> CreateEnumOption<T>(T @default)
where T : notnull, Enum
{
var option = CodeStyleOption2<T>.Default;
option = (CodeStyleOption2<T>)((ICodeStyleOption)option).WithValue(@default);
return new Option2<CodeStyleOption2<T>>(feature: "TestFeature",
name: "TestOption",
defaultValue: option);
}
private class TestAnalyzerConfigOptions : AnalyzerConfigOptions
{
private readonly IDictionary<string, string> _dictionary;
public TestAnalyzerConfigOptions((string, string)[]? options = null)
=> _dictionary = options?.ToDictionary(x => x.Item1, x => x.Item2) ?? new Dictionary<string, string>();
public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value)
=> _dictionary.TryGetValue(key, out value);
}
private class TestOptionSet<T> : OptionSet
{
private readonly object? _value;
public TestOptionSet(CodeStyleOption2<T> value) => _value = value;
public override OptionSet WithChangedOption(OptionKey optionAndLanguage, object? value) => this;
internal override IEnumerable<OptionKey> GetChangedOptions(OptionSet optionSet) => Array.Empty<OptionKey>();
private protected override object? GetOptionCore(OptionKey optionKey) => _value;
}
}
}
| -1 |
|
dotnet/roslyn | 55,484 | Remove obsolete UnitTesting and Razor External Access APIs | tmat | 2021-08-06T23:36:46Z | 2021-08-10T20:32:36Z | 909e6dc8eda8ee5898b4e1339c512c44970bcff6 | 3d0d94801b78fd6d22afb36d26c834f5056e7e62 | Remove obsolete UnitTesting and Razor External Access APIs. | ./src/Compilers/Test/Resources/Core/MetadataTests/InterfaceAndClass/VBInterfaces01.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L O8N ! .5 @ @ @ 4 W @ ` H .text 4 `.rsrc @ @ @.reloc ` @ B 5 H 0" (
*(
*s
s
s
s
* 0 ~ o
+ * 0 ~ o
+ * 0 ~ o
+ * 0 ~ o
+ * 0 (
(
+ * 0 (
+ * 0 (
+ * 0 (
+ * 0 -
( +
++
+ *0
*(
*0 , {
o
-( +{
o
+ *J(
s
}
* :(
} * 0 {
+ * "} * BSJB v4.0.30319 l #~ t @ #Strings #US #GUID #Blob W %3 ' ! + -
s
sI %
d=
| (
A p ) 7 : 7 E 7
O
]
x ~ !
# 1 6 1 _- 1 : 1 G ! *P X ` " ) O( x5 B Fc ! Fh 4! l P! Fq h! x ! % ! ! 9 ! Fq F F F Fq F
F F5 F F F F F F F F ! " F1 $" FC F\ Fj 2 2 V
$ 9 I - Q $ , 4 < |