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,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/VisualStudio/Core/Test/CodeModel/VisualBasic/ExternalCodeFunctionTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class ExternalCodeFunctionTests
Inherits AbstractCodeFunctionTests
#Region "FullName tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFullName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestFullName(code, "C.Goo")
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestName(code, "Goo")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Roslyn.Test.Utilities
Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel.VisualBasic
Public Class ExternalCodeFunctionTests
Inherits AbstractCodeFunctionTests
#Region "FullName tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestFullName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestFullName(code, "C.Goo")
End Sub
#End Region
#Region "Name tests"
<WpfFact, Trait(Traits.Feature, Traits.Features.CodeModel)>
Public Sub TestName1()
Dim code =
<Code>
Class C
Sub $$Goo(string s)
End Sub
End Class
</Code>
TestName(code, "Goo")
End Sub
#End Region
Protected Overrides ReadOnly Property LanguageName As String = LanguageNames.VisualBasic
Protected Overrides ReadOnly Property TargetExternalCodeElements As Boolean = True
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Workspaces/Core/Portable/FindSymbols/SearchKind.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal enum SearchKind
{
/// <summary>
/// Use an case-sensitive comparison when searching for matching items.
/// </summary>
Exact,
/// <summary>
/// Use a case-insensitive comparison when searching for matching items.
/// </summary>
ExactIgnoreCase,
/// <summary>
/// Use a fuzzy comparison when searching for matching items. Fuzzy matching allows for
/// a certain amount of misspellings, missing words, etc. See <see cref="SpellChecker"/> for
/// more details.
/// </summary>
Fuzzy,
/// <summary>
/// Search term is matched in a custom manner (i.e. with a user provided predicate).
/// </summary>
Custom
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal enum SearchKind
{
/// <summary>
/// Use an case-sensitive comparison when searching for matching items.
/// </summary>
Exact,
/// <summary>
/// Use a case-insensitive comparison when searching for matching items.
/// </summary>
ExactIgnoreCase,
/// <summary>
/// Use a fuzzy comparison when searching for matching items. Fuzzy matching allows for
/// a certain amount of misspellings, missing words, etc. See <see cref="SpellChecker"/> for
/// more details.
/// </summary>
Fuzzy,
/// <summary>
/// Search term is matched in a custom manner (i.e. with a user provided predicate).
/// </summary>
Custom
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Features/CSharp/Portable/IntroduceVariable/CSharpIntroduceVariableService_IntroduceQueryLocal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
private static bool IsAnyQueryClause(SyntaxNode node)
=> node is QueryClauseSyntax || node is SelectOrGroupClauseSyntax;
protected override Task<Document> IntroduceQueryLocalAsync(
SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken)
{
var oldOutermostQuery = expression.GetAncestorsOrThis<QueryExpressionSyntax>().LastOrDefault();
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant: false,
containerOpt: oldOutermostQuery, cancellationToken: cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var letClause = SyntaxFactory.LetClause(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
expression).WithAdditionalAnnotations(Formatter.Annotation);
var matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken);
var innermostClauses = new HashSet<SyntaxNode>(
matches.Select(expr => expr.GetAncestorsOrThis<SyntaxNode>().First(IsAnyQueryClause)));
if (innermostClauses.Count == 1)
{
// If there was only one match, or all the matches came from the same
// statement, then we want to place the declaration right above that
// statement. Note: we special case this because the statement we are going
// to go above might not be in a block and we may have to generate it
return Task.FromResult(IntroduceQueryLocalForSingleOccurrence(
document, expression, newLocalName, letClause, allOccurrences, cancellationToken));
}
var oldInnerMostCommonQuery = matches.FindInnermostCommonNode<QueryExpressionSyntax>();
var newInnerMostQuery = Rewrite(
document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken);
var allAffectedClauses = new HashSet<SyntaxNode>(matches.SelectMany(expr => expr.GetAncestorsOrThis<SyntaxNode>().Where(IsAnyQueryClause)));
var oldClauses = oldInnerMostCommonQuery.GetAllClauses();
var newClauses = newInnerMostQuery.GetAllClauses();
var firstClauseAffectedInQuery = oldClauses.First(allAffectedClauses.Contains);
var firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery);
var finalClauses = newClauses.Take(firstClauseAffectedIndex)
.Concat(letClause)
.Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList();
var finalQuery = newInnerMostQuery.WithAllClauses(finalClauses);
var newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery);
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
private Document IntroduceQueryLocalForSingleOccurrence(
SemanticDocument document,
ExpressionSyntax expression,
NameSyntax newLocalName,
LetClauseSyntax letClause,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldClause = expression.GetAncestors<SyntaxNode>().First(IsAnyQueryClause);
var newClause = Rewrite(
document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken);
var oldQuery = (QueryBodySyntax)oldClause.Parent;
var newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause);
var newRoot = document.Root.ReplaceNode(oldQuery, newQuery);
return document.Document.WithSyntaxRoot(newRoot);
}
private static QueryBodySyntax GetNewQuery(
QueryBodySyntax oldQuery,
SyntaxNode oldClause,
SyntaxNode newClause,
LetClauseSyntax letClause)
{
var oldClauses = oldQuery.GetAllClauses();
var oldClauseIndex = oldClauses.IndexOf(oldClause);
var newClauses = oldClauses.Take(oldClauseIndex)
.Concat(letClause)
.Concat(newClause)
.Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList();
return oldQuery.WithAllClauses(newClauses);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.IntroduceVariable
{
internal partial class CSharpIntroduceVariableService
{
private static bool IsAnyQueryClause(SyntaxNode node)
=> node is QueryClauseSyntax || node is SelectOrGroupClauseSyntax;
protected override Task<Document> IntroduceQueryLocalAsync(
SemanticDocument document, ExpressionSyntax expression, bool allOccurrences, CancellationToken cancellationToken)
{
var oldOutermostQuery = expression.GetAncestorsOrThis<QueryExpressionSyntax>().LastOrDefault();
var newLocalNameToken = GenerateUniqueLocalName(
document, expression, isConstant: false,
containerOpt: oldOutermostQuery, cancellationToken: cancellationToken);
var newLocalName = SyntaxFactory.IdentifierName(newLocalNameToken);
var letClause = SyntaxFactory.LetClause(
newLocalNameToken.WithAdditionalAnnotations(RenameAnnotation.Create()),
expression).WithAdditionalAnnotations(Formatter.Annotation);
var matches = FindMatches(document, expression, document, oldOutermostQuery, allOccurrences, cancellationToken);
var innermostClauses = new HashSet<SyntaxNode>(
matches.Select(expr => expr.GetAncestorsOrThis<SyntaxNode>().First(IsAnyQueryClause)));
if (innermostClauses.Count == 1)
{
// If there was only one match, or all the matches came from the same
// statement, then we want to place the declaration right above that
// statement. Note: we special case this because the statement we are going
// to go above might not be in a block and we may have to generate it
return Task.FromResult(IntroduceQueryLocalForSingleOccurrence(
document, expression, newLocalName, letClause, allOccurrences, cancellationToken));
}
var oldInnerMostCommonQuery = matches.FindInnermostCommonNode<QueryExpressionSyntax>();
var newInnerMostQuery = Rewrite(
document, expression, newLocalName, document, oldInnerMostCommonQuery, allOccurrences, cancellationToken);
var allAffectedClauses = new HashSet<SyntaxNode>(matches.SelectMany(expr => expr.GetAncestorsOrThis<SyntaxNode>().Where(IsAnyQueryClause)));
var oldClauses = oldInnerMostCommonQuery.GetAllClauses();
var newClauses = newInnerMostQuery.GetAllClauses();
var firstClauseAffectedInQuery = oldClauses.First(allAffectedClauses.Contains);
var firstClauseAffectedIndex = oldClauses.IndexOf(firstClauseAffectedInQuery);
var finalClauses = newClauses.Take(firstClauseAffectedIndex)
.Concat(letClause)
.Concat(newClauses.Skip(firstClauseAffectedIndex)).ToList();
var finalQuery = newInnerMostQuery.WithAllClauses(finalClauses);
var newRoot = document.Root.ReplaceNode(oldInnerMostCommonQuery, finalQuery);
return Task.FromResult(document.Document.WithSyntaxRoot(newRoot));
}
private Document IntroduceQueryLocalForSingleOccurrence(
SemanticDocument document,
ExpressionSyntax expression,
NameSyntax newLocalName,
LetClauseSyntax letClause,
bool allOccurrences,
CancellationToken cancellationToken)
{
var oldClause = expression.GetAncestors<SyntaxNode>().First(IsAnyQueryClause);
var newClause = Rewrite(
document, expression, newLocalName, document, oldClause, allOccurrences, cancellationToken);
var oldQuery = (QueryBodySyntax)oldClause.Parent;
var newQuery = GetNewQuery(oldQuery, oldClause, newClause, letClause);
var newRoot = document.Root.ReplaceNode(oldQuery, newQuery);
return document.Document.WithSyntaxRoot(newRoot);
}
private static QueryBodySyntax GetNewQuery(
QueryBodySyntax oldQuery,
SyntaxNode oldClause,
SyntaxNode newClause,
LetClauseSyntax letClause)
{
var oldClauses = oldQuery.GetAllClauses();
var oldClauseIndex = oldClauses.IndexOf(oldClause);
var newClauses = oldClauses.Take(oldClauseIndex)
.Concat(letClause)
.Concat(newClause)
.Concat(oldClauses.Skip(oldClauseIndex + 1)).ToList();
return oldQuery.WithAllClauses(newClauses);
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/CSharpTest/ChangeSignature/AddParameterTests.OptionalParameter.Infer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_NoOptions()
{
var markup = @"
class C
{
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
M(TODO);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleLocal()
{
var markup = @"
class C
{
void M$$()
{
int x = 7;
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
int x = 7;
M(x);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_NotOnInaccessibleLocal()
{
var markup = @"
class C
{
void M$$()
{
M();
int x = 7;
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
M(TODO);
int x = 7;
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_MultipleLocals()
{
var markup = @"
class C
{
void M$$()
{
int x = 7;
int y = 8;
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
int x = 7;
int y = 8;
M(y);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleParameter()
{
var markup = @"
class C
{
void M$$(int x)
{
M(1);
}
}";
var updatedSignature = new[] {
new AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int x, int a)
{
M(1, x);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleField()
{
var markup = @"
class C
{
int x = 8;
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
int x = 8;
void M(int a)
{
M(x);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleProperty()
{
var markup = @"
class C
{
int X { get; set; }
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
int X { get; set; }
void M(int a)
{
M(X);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable()
{
var markup = @"
class B { }
class D : B { }
class C
{
void M$$()
{
D d = null;
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred) };
var updatedCode = @"
class B { }
class D : B { }
class C
{
void M(B b)
{
D d = null;
M(d);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation 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.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.UnitTests.ChangeSignature;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities.ChangeSignature;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ChangeSignature
{
public partial class ChangeSignatureTests : AbstractChangeSignatureTests
{
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_NoOptions()
{
var markup = @"
class C
{
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
M(TODO);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleLocal()
{
var markup = @"
class C
{
void M$$()
{
int x = 7;
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
int x = 7;
M(x);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_NotOnInaccessibleLocal()
{
var markup = @"
class C
{
void M$$()
{
M();
int x = 7;
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
M(TODO);
int x = 7;
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_MultipleLocals()
{
var markup = @"
class C
{
void M$$()
{
int x = 7;
int y = 8;
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int a)
{
int x = 7;
int y = 8;
M(y);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleParameter()
{
var markup = @"
class C
{
void M$$(int x)
{
M(1);
}
}";
var updatedSignature = new[] {
new AddedParameterOrExistingIndex(0),
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
void M(int x, int a)
{
M(1, x);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleField()
{
var markup = @"
class C
{
int x = 8;
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
int x = 8;
void M(int a)
{
M(x);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_SingleProperty()
{
var markup = @"
class C
{
int X { get; set; }
void M$$()
{
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("System.Int32", "a", CallSiteKind.Inferred) };
var updatedCode = @"
class C
{
int X { get; set; }
void M(int a)
{
M(X);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
[Fact, Trait(Traits.Feature, Traits.Features.ChangeSignature)]
public async Task AddOptionalParameter_CallsiteInferred_ImplicitlyConvertable()
{
var markup = @"
class B { }
class D : B { }
class C
{
void M$$()
{
D d = null;
M();
}
}";
var updatedSignature = new[] {
AddedParameterOrExistingIndex.CreateAdded("B", "b", CallSiteKind.Inferred) };
var updatedCode = @"
class B { }
class D : B { }
class C
{
void M(B b)
{
D d = null;
M(d);
}
}";
await TestChangeSignatureViaCommandAsync(LanguageNames.CSharp, markup, updatedSignature: updatedSignature, expectedUpdatedInvocationDocumentCode: updatedCode);
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/CSharpTest/SignatureHelp/GenericNamePartiallyWrittenSignatureHelpProviderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(GenericNamePartiallyWrittenSignatureHelpProvider);
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedGenericUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Goo()
{
G<G<int>$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task DeclaringGenericTypeWith1ParameterUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Goo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task CallingGenericAsyncMethod()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void Main(string[] args)
{
Goo<$$
}
Task<int> Goo<T>()
{
return Goo<T>();
}
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task<int> Program.Goo<T>()", methodDocumentation: string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Enable the script case when we have support for extension methods in scripts
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Goo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Goo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Goo<T>(T x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo<T, U>(T x, U y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task GenericExtensionMethod()
{
var markup = @"
interface IGoo
{
void Bar<T>();
}
static class GooExtensions
{
public static void Bar<T1, T2>(this IGoo goo) { }
}
class Program
{
static void Main()
{
IGoo f = null;
f.[|Bar<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IGoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokingGenericMethodWith1ParameterUnterminated()
{
var markup = @"
class C
{
/// <summary>
/// Method Goo
/// </summary>
/// <typeparam name=""T"">Method type parameter</typeparam>
void Goo<T>() { }
void Bar()
{
[|Goo<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>()",
"Method Goo", "Method type parameter", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerBracket()
{
var markup = @"
class G<S, T> { };
class C
{
void Goo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class G<S, T> { };
class C
{
void Goo()
{
[|G<int,$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// goo<$$";
await TestAsync(markup);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.SignatureHelp;
using Microsoft.CodeAnalysis.Editor.UnitTests.SignatureHelp;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.SignatureHelp
{
public class GenericNamePartiallyWrittenSignatureHelpProviderTests : AbstractCSharpSignatureHelpProviderTests
{
internal override Type GetSignatureHelpProviderType()
=> typeof(GenericNamePartiallyWrittenSignatureHelpProvider);
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task NestedGenericUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Goo()
{
G<G<int>$$
}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task DeclaringGenericTypeWith1ParameterUnterminated()
{
var markup = @"
class G<T> { };
class C
{
void Goo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task CallingGenericAsyncMethod()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
void Main(string[] args)
{
Goo<$$
}
Task<int> Goo<T>()
{
return Goo<T>();
}
}
";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem($"({CSharpFeaturesResources.awaitable}) Task<int> Program.Goo<T>()", methodDocumentation: string.Empty, string.Empty, currentParameterIndex: 0));
// TODO: Enable the script case when we have support for extension methods in scripts
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: false, sourceCodeKind: Microsoft.CodeAnalysis.SourceCodeKind.Regular);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableAlways()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Goo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableNever()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableAdvanced()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
public void Goo<T>(T x)
{ }
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItems,
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: false);
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: new List<SignatureHelpTestItem>(),
expectedOrderedItemsSameSolution: expectedOrderedItems,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp,
hideAdvancedMembers: true);
}
[WorkItem(7336, "DevDiv_Projects/Roslyn")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task EditorBrowsable_GenericMethod_BrowsableMixed()
{
var markup = @"
class Program
{
void M()
{
new C().Goo<$$
}
}
";
var referencedCode = @"
public class C
{
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Always)]
public void Goo<T>(T x)
{ }
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public void Goo<T, U>(T x, U y)
{ }
}";
var expectedOrderedItemsMetadataReference = new List<SignatureHelpTestItem>();
expectedOrderedItemsMetadataReference.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
var expectedOrderedItemsSameSolution = new List<SignatureHelpTestItem>();
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T>(T x)", string.Empty, string.Empty, currentParameterIndex: 0));
expectedOrderedItemsSameSolution.Add(new SignatureHelpTestItem("void C.Goo<T, U>(T x, U y)", string.Empty, string.Empty, currentParameterIndex: 0));
await TestSignatureHelpInEditorBrowsableContextsAsync(markup: markup,
referencedCode: referencedCode,
expectedOrderedItemsMetadataReference: expectedOrderedItemsMetadataReference,
expectedOrderedItemsSameSolution: expectedOrderedItemsSameSolution,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.CSharp);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task GenericExtensionMethod()
{
var markup = @"
interface IGoo
{
void Bar<T>();
}
static class GooExtensions
{
public static void Bar<T1, T2>(this IGoo goo) { }
}
class Program
{
static void Main()
{
IGoo f = null;
f.[|Bar<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>
{
new SignatureHelpTestItem("void IGoo.Bar<T>()", currentParameterIndex: 0),
new SignatureHelpTestItem($"({CSharpFeaturesResources.extension}) void IGoo.Bar<T1, T2>()", currentParameterIndex: 0),
};
// Extension methods are supported in Interactive/Script (yet).
await TestAsync(markup, expectedOrderedItems, sourceCodeKind: SourceCodeKind.Regular);
}
[WorkItem(544088, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544088")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokingGenericMethodWith1ParameterUnterminated()
{
var markup = @"
class C
{
/// <summary>
/// Method Goo
/// </summary>
/// <typeparam name=""T"">Method type parameter</typeparam>
void Goo<T>() { }
void Bar()
{
[|Goo<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("void C.Goo<T>()",
"Method Goo", "Method type parameter", currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerBracket()
{
var markup = @"
class G<S, T> { };
class C
{
void Goo()
{
[|G<$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 0));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task TestInvocationOnTriggerComma()
{
var markup = @"
class G<S, T> { };
class C
{
void Goo()
{
[|G<int,$$
|]}
}";
var expectedOrderedItems = new List<SignatureHelpTestItem>();
expectedOrderedItems.Add(new SignatureHelpTestItem("G<S, T>", string.Empty, string.Empty, currentParameterIndex: 1));
await TestAsync(markup, expectedOrderedItems, usePreviousCharAsTrigger: true);
}
[WorkItem(1067933, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067933")]
[Fact, Trait(Traits.Feature, Traits.Features.SignatureHelp)]
public async Task InvokedWithNoToken()
{
var markup = @"
// goo<$$";
await TestAsync(markup);
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/Server/VBCSCompilerTests/TestableClientConnection.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
internal sealed class TestableClientConnection : IClientConnection
{
public string LoggingIdentifier { get; set; } = "TestableClient";
public Task DisconnectTask { get; set; } = new TaskCompletionSource<object>().Task;
public Action DisposeFunc { get; set; } = delegate { };
public Func<CancellationToken, Task<BuildRequest>> ReadBuildRequestFunc = delegate { throw new Exception(); };
public Func<BuildResponse, CancellationToken, Task> WriteBuildResponseFunc = delegate { throw new Exception(); };
public void Dispose() => DisposeFunc();
public Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken) => ReadBuildRequestFunc(cancellationToken);
public Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken) => WriteBuildResponseFunc(response, cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CommandLine;
namespace Microsoft.CodeAnalysis.CompilerServer.UnitTests
{
internal sealed class TestableClientConnection : IClientConnection
{
public string LoggingIdentifier { get; set; } = "TestableClient";
public Task DisconnectTask { get; set; } = new TaskCompletionSource<object>().Task;
public Action DisposeFunc { get; set; } = delegate { };
public Func<CancellationToken, Task<BuildRequest>> ReadBuildRequestFunc = delegate { throw new Exception(); };
public Func<BuildResponse, CancellationToken, Task> WriteBuildResponseFunc = delegate { throw new Exception(); };
public void Dispose() => DisposeFunc();
public Task<BuildRequest> ReadBuildRequestAsync(CancellationToken cancellationToken) => ReadBuildRequestFunc(cancellationToken);
public Task WriteBuildResponseAsync(BuildResponse response, CancellationToken cancellationToken) => WriteBuildResponseFunc(response, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/VisualBasic/Portable/Symbols/TypeSubstitution.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.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Immutable. Thread-safe.
'''
''' Represents a type substitution, with substitutions of types for a set of type parameters.
''' Each TypeSubstitution object has three pieces of information:
''' - OriginalDefinition of generic symbol the substitution is targeting.
''' - An array of pairs that provide a mapping from symbol's type parameters to type arguments.
''' identity substitutions are omitted.
''' - TypeSubstitution object for containing type to provide mapping for its type
''' parameters, if any.
'''
''' The identity substitution (for the whole type hierarchy) is represented by Nothing. That said,
''' top level parent of non-Nothing instance of TypeSubstitution is guaranteed to be non-identity
''' substitution. The instance may still be an identity substitution just for target generic definition,
''' which will be represented by an empty mapping array.
'''
''' The chain of TypeSubstitution objects is guaranteed to not skip any type in the containership hierarchy,
''' even types with zero arity contained in generic type will have corresponding TypeSubstitution object with
''' empty mapping array.
'''
''' Example:
''' Class A(Of T,S)
''' Class B
''' Class C(Of U)
''' End Class
''' End Class
''' End Class
'''
''' TypeSubstitution for A(Of Integer, S).B.C(Of Byte) is C{U->Byte}=>B{}=>A{T->Integer}
''' TypeSubstitution for A(Of T, S).B.C(Of Byte) is C{U->Byte}
''' TypeSubstitution for A(Of Integer, S).B is B{}=>A{T->Integer}
''' TypeSubstitution for A(Of Integer, S).B.C(Of U) is C{}=>B{}=>A{T->Integer}
'''
''' CONSIDER:
''' An array of KeyValuePair(Of TypeParameterSymbol, TypeSymbol)objects is used to represent type
''' parameter substitution mostly due to historical reasons. It might be more convenient and more
''' efficient to use ordinal based array of TypeSymbol objects instead.
'''
''' There is a Construct method that can be called on original definition with TypeSubstitution object as
''' an argument. The advantage of that method is the ability to substitute type parameters of several types
''' in the containership hierarchy in one call. What type the TypeSubstitution parameter targets makes a
''' difference.
'''
''' For example:
''' C.Construct(C{}=>B{}=>A{T->Integer}) == A(Of Integer, S).B.C(Of U)
''' C.Construct(B{}=>A{T->Integer}) == A(Of Integer, S).B.C(Of )
''' B.Construct(B{}=>A{T->Integer}) == A(Of Integer, S).B
'''
''' See comment for IsValidToApplyTo method as well.
''' </summary>
Friend Class TypeSubstitution
''' <summary>
''' A map between type parameters of _targetGenericDefinition and corresponding type arguments.
''' Represented by an array of Key-Value pairs. Keys are type parameters of _targetGenericDefinition
''' in no particular order. Identity substitutions are omitted.
''' </summary>
Private ReadOnly _pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
''' <summary>
''' Definition of a symbol which this instance of TypeSubstitution primarily targets.
''' </summary>
Private ReadOnly _targetGenericDefinition As Symbol
''' <summary>
''' An instance of TypeSubstitution describing substitution for containing type.
''' </summary>
Private ReadOnly _parent As TypeSubstitution
Public ReadOnly Property Pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
Get
Return _pairs
End Get
End Property
''' <summary>
''' Get all the pairs of substitutions, including from the parent substitutions. The substitutions
''' are in order from outside-in (parent substitutions before child substitutions).
''' </summary>
Public ReadOnly Property PairsIncludingParent As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
Get
If _parent Is Nothing Then
Return Pairs
Else
Dim pairBuilder = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
AddPairsIncludingParentToBuilder(pairBuilder)
Return pairBuilder.ToImmutableAndFree()
End If
End Get
End Property
'Add pairs (including parent pairs) to the given array builder.
Private Sub AddPairsIncludingParentToBuilder(pairBuilder As ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)))
If _parent IsNot Nothing Then
_parent.AddPairsIncludingParentToBuilder(pairBuilder)
End If
pairBuilder.AddRange(_pairs)
End Sub
Public ReadOnly Property Parent As TypeSubstitution
Get
Return _parent
End Get
End Property
Public ReadOnly Property TargetGenericDefinition As Symbol
Get
Return _targetGenericDefinition
End Get
End Property
' If this substitution contains the given type parameter, return the substituted type.
' Otherwise, returns the type parameter itself.
Public Function GetSubstitutionFor(tp As TypeParameterSymbol) As TypeWithModifiers
Debug.Assert(tp IsNot Nothing)
Debug.Assert(tp.IsDefinition OrElse TargetGenericDefinition Is tp.ContainingSymbol)
Dim containingSymbol As Symbol = tp.ContainingSymbol
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is containingSymbol Then
For Each p In current.Pairs
If p.Key.Equals(tp) Then Return p.Value
Next
' not found, return the passed in type parameters
Return New TypeWithModifiers(tp, ImmutableArray(Of CustomModifier).Empty)
End If
current = current.Parent
Loop While current IsNot Nothing
' not found, return the passed in type parameters
Return New TypeWithModifiers(tp, ImmutableArray(Of CustomModifier).Empty)
End Function
Public Function GetTypeArgumentsFor(originalDefinition As NamedTypeSymbol, <Out> ByRef hasTypeArgumentsCustomModifiers As Boolean) As ImmutableArray(Of TypeSymbol)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Dim result = ArrayBuilder(Of TypeSymbol).GetInstance(originalDefinition.Arity, fillWithValue:=Nothing)
hasTypeArgumentsCustomModifiers = False
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
result(p.Key.Ordinal) = p.Value.Type
If Not p.Value.CustomModifiers.IsDefaultOrEmpty Then
hasTypeArgumentsCustomModifiers = True
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
For i As Integer = 0 To result.Count - 1
If result(i) Is Nothing Then
result(i) = originalDefinition.TypeParameters(i)
End If
Next
Return result.ToImmutableAndFree()
End Function
Public Function GetTypeArgumentsCustomModifiersFor(originalDefinition As TypeParameterSymbol) As ImmutableArray(Of CustomModifier)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is originalDefinition.ContainingSymbol Then
For Each p In current.Pairs
If p.Key.Ordinal = originalDefinition.Ordinal Then
Return p.Value.CustomModifiers
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
Return ImmutableArray(Of CustomModifier).Empty
End Function
Public Function HasTypeArgumentsCustomModifiersFor(originalDefinition As NamedTypeSymbol) As Boolean
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
If Not p.Value.CustomModifiers.IsDefaultOrEmpty Then
Return True
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
Return False
End Function
''' <summary>
''' Verify TypeSubstitution to make sure it doesn't map any
''' type parameter to an alpha-renamed type parameter.
''' </summary>
''' <remarks></remarks>
Public Sub ThrowIfSubstitutingToAlphaRenamedTypeParameter()
Dim toCheck As TypeSubstitution = Me
Do
For Each pair In toCheck.Pairs
Dim value As TypeSymbol = pair.Value.Type
If value.IsTypeParameter() AndAlso Not value.IsDefinition Then
Throw New ArgumentException()
End If
Next
toCheck = toCheck.Parent
Loop While toCheck IsNot Nothing
End Sub
''' <summary>
''' Return TypeSubstitution instance that targets particular generic definition.
''' </summary>
Public Function GetSubstitutionForGenericDefinition(
targetGenericDefinition As Symbol
) As TypeSubstitution
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is targetGenericDefinition Then
Return current
End If
current = current.Parent
Loop While current IsNot Nothing
Return Nothing
End Function
''' <summary>
''' Return TypeSubstitution instance that targets particular
''' generic definition or one of its containers.
''' </summary>
Public Function GetSubstitutionForGenericDefinitionOrContainers(
targetGenericDefinition As Symbol
) As TypeSubstitution
Dim current As TypeSubstitution = Me
Do
If current.IsValidToApplyTo(targetGenericDefinition) Then
Return current
End If
current = current.Parent
Loop While current IsNot Nothing
Return Nothing
End Function
''' <summary>
''' Does substitution target either genericDefinition or
''' one of its containers?
''' </summary>
Public Function IsValidToApplyTo(genericDefinition As Symbol) As Boolean
Debug.Assert(genericDefinition.IsDefinition)
Dim current As Symbol = genericDefinition
Do
If current Is Me.TargetGenericDefinition Then
Return True
End If
current = current.ContainingType
Loop While current IsNot Nothing
Return False
End Function
''' <summary>
''' Combine two substitutions into one by concatenating.
'''
''' They may not directly or indirectly (through Parent) target the same generic definition.
''' sub2 is expected to target types lower in the containership hierarchy.
''' Either or both can be Nothing.
'''
''' targetGenericDefinition specifies target generic definition for the result.
''' If sub2 is not Nothing, it must target targetGenericDefinition.
''' If sub2 is Nothing, sub1 will be "extended" with identity substitutions to target
''' targetGenericDefinition.
''' </summary>
Public Shared Function Concat(targetGenericDefinition As Symbol, sub1 As TypeSubstitution, sub2 As TypeSubstitution) As TypeSubstitution
Debug.Assert(targetGenericDefinition.IsDefinition)
Debug.Assert(sub2 Is Nothing OrElse sub2.TargetGenericDefinition Is targetGenericDefinition)
If sub1 Is Nothing Then
Return sub2
Else
Debug.Assert(sub1.TargetGenericDefinition.IsDefinition)
If sub2 Is Nothing Then
If targetGenericDefinition Is sub1.TargetGenericDefinition Then
Return sub1
End If
Return Concat(sub1, targetGenericDefinition, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty)
Else
Return ConcatNotNulls(sub1, sub2)
End If
End If
End Function
Private Shared Function ConcatNotNulls(sub1 As TypeSubstitution, sub2 As TypeSubstitution) As TypeSubstitution
If sub2.Parent Is Nothing Then
Return Concat(sub1, sub2.TargetGenericDefinition, sub2.Pairs)
Else
Return Concat(ConcatNotNulls(sub1, sub2.Parent), sub2.TargetGenericDefinition, sub2.Pairs)
End If
End Function
''' <summary>
''' Create a substitution. If the substitution is the identity substitution, Nothing is returned.
''' </summary>
''' <param name="targetGenericDefinition">Generic definition the result should target.</param>
''' <param name="params">
''' Type parameter definitions. Duplicates aren't allowed. Type parameters of containing type
''' must precede type parameters of a nested type.
''' </param>
''' <param name="args">Corresponding type arguments.</param>
''' <returns></returns>
Public Shared Function Create(
targetGenericDefinition As Symbol,
params() As TypeParameterSymbol,
args() As TypeWithModifiers,
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition, params.AsImmutableOrNull, args.AsImmutableOrNull, allowAlphaRenamedTypeParametersAsArguments)
End Function
Public Shared Function Create(
targetGenericDefinition As Symbol,
params() As TypeParameterSymbol,
args() As TypeSymbol,
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition, params.AsImmutableOrNull, args.AsImmutableOrNull, allowAlphaRenamedTypeParametersAsArguments)
End Function
''' <summary>
''' Create a substitution. If the substitution is the identity substitution, Nothing is returned.
''' </summary>
''' <param name="targetGenericDefinition">Generic definition the result should target.</param>
''' <param name="params">
''' Type parameter definitions. Duplicates aren't allowed. Type parameters of containing type
''' must precede type parameters of a nested type.
''' </param>
''' <param name="args">Corresponding type arguments.</param>
''' <returns></returns>
Public Shared Function Create(
targetGenericDefinition As Symbol,
params As ImmutableArray(Of TypeParameterSymbol),
args As ImmutableArray(Of TypeWithModifiers),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Debug.Assert(targetGenericDefinition.IsDefinition)
If params.Length <> args.Length Then
Throw New ArgumentException(VBResources.NumberOfTypeParametersAndArgumentsMustMatch)
End If
Dim currentParent As TypeSubstitution = Nothing
Dim currentContainer As Symbol = Nothing
#If DEBUG Then
Dim haveSubstitutionForOrdinal = BitVector.Create(params.Length)
#End If
Dim pairs = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
Try
For i = 0 To params.Length - 1
Dim param As TypeParameterSymbol = params(i)
Dim arg As TypeWithModifiers = args(i)
Debug.Assert(param.IsDefinition)
If currentContainer IsNot param.ContainingSymbol Then
' starting new segment, finish the current one
If pairs.Count > 0 Then
currentParent = Concat(currentParent, currentContainer, pairs.ToImmutable())
pairs.Clear()
End If
currentContainer = param.ContainingSymbol
#If DEBUG Then
haveSubstitutionForOrdinal.Clear()
#End If
End If
#If DEBUG Then
Debug.Assert(Not haveSubstitutionForOrdinal(param.Ordinal))
haveSubstitutionForOrdinal(param.Ordinal) = True
#End If
If arg.Is(param) Then
Continue For
End If
If Not allowAlphaRenamedTypeParametersAsArguments Then
' Can't use alpha-renamed type parameters as arguments
If arg.Type.IsTypeParameter() AndAlso Not arg.Type.IsDefinition Then
Throw New ArgumentException()
End If
End If
pairs.Add(New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(param, arg))
Next
' finish the current segment
If pairs.Count > 0 Then
currentParent = Concat(currentParent, currentContainer, pairs.ToImmutable())
End If
Finally
pairs.Free()
End Try
If currentParent IsNot Nothing AndAlso currentParent.TargetGenericDefinition IsNot targetGenericDefinition Then
currentParent = Concat(currentParent, targetGenericDefinition, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty)
#If DEBUG Then
ElseIf currentContainer IsNot Nothing AndAlso currentContainer IsNot targetGenericDefinition Then
' currentContainer must be either targetGenericDefinition or a container of targetGenericDefinition
Dim container As NamedTypeSymbol = targetGenericDefinition.ContainingType
While container IsNot Nothing AndAlso container IsNot currentContainer
container = container.ContainingType
End While
Debug.Assert(container Is currentContainer)
#End If
End If
Return currentParent
End Function
Private Shared ReadOnly s_withoutModifiers As Func(Of TypeSymbol, TypeWithModifiers) = Function(arg) New TypeWithModifiers(arg)
Public Shared Function Create(
targetGenericDefinition As Symbol,
params As ImmutableArray(Of TypeParameterSymbol),
args As ImmutableArray(Of TypeSymbol),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition,
params,
args.SelectAsArray(s_withoutModifiers),
allowAlphaRenamedTypeParametersAsArguments)
End Function
Public Shared Function Create(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
args As ImmutableArray(Of TypeSymbol),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(parent,
targetGenericDefinition,
args.SelectAsArray(s_withoutModifiers),
allowAlphaRenamedTypeParametersAsArguments)
End Function
''' <summary>
''' Private helper to make sure identity substitutions are injected for types between
''' targetGenericDefinition and parent.TargetGenericDefinition.
''' </summary>
Private Shared Function Concat(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
) As TypeSubstitution
If parent Is Nothing OrElse parent.TargetGenericDefinition Is targetGenericDefinition.ContainingType Then
Return New TypeSubstitution(targetGenericDefinition, pairs, parent)
End If
Dim containingType As NamedTypeSymbol = targetGenericDefinition.ContainingType
Debug.Assert(containingType IsNot Nothing)
Return New TypeSubstitution(
targetGenericDefinition,
pairs,
Concat(parent, containingType, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty))
End Function
Public Overrides Function ToString() As String
Dim builder As New StringBuilder()
builder.AppendFormat("{0} : ", TargetGenericDefinition)
ToString(builder)
Return builder.ToString()
End Function
Private Overloads Sub ToString(builder As StringBuilder)
If _parent IsNot Nothing Then
_parent.ToString(builder)
builder.Append(", ")
End If
builder.Append("{"c)
For i = 0 To _pairs.Length - 1
If i <> 0 Then
builder.Append(", ")
End If
builder.AppendFormat("{0}->{1}", _pairs(i).Key.ToString(), _pairs(i).Value.Type.ToString())
Next
builder.Append("}"c)
End Sub
Private Sub New(targetGenericDefinition As Symbol, pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)), parent As TypeSubstitution)
Debug.Assert(Not pairs.IsDefault)
Debug.Assert(pairs.All(Function(p) p.Key IsNot Nothing))
Debug.Assert(pairs.All(Function(p) p.Value.Type IsNot Nothing))
Debug.Assert(pairs.All(Function(p) Not p.Value.CustomModifiers.IsDefault))
Debug.Assert(targetGenericDefinition IsNot Nothing AndAlso
(targetGenericDefinition.IsDefinition OrElse
(targetGenericDefinition.Kind = SymbolKind.Method AndAlso
DirectCast(targetGenericDefinition, MethodSymbol).ConstructedFrom Is targetGenericDefinition AndAlso
parent Is Nothing)))
Debug.Assert((targetGenericDefinition.Kind = SymbolKind.Method AndAlso
(DirectCast(targetGenericDefinition, MethodSymbol).IsGenericMethod OrElse
(targetGenericDefinition.ContainingType.IsOrInGenericType() AndAlso parent IsNot Nothing))) OrElse
((targetGenericDefinition.Kind = SymbolKind.NamedType OrElse targetGenericDefinition.Kind = SymbolKind.ErrorType) AndAlso
DirectCast(targetGenericDefinition, NamedTypeSymbol).IsOrInGenericType()))
Debug.Assert(parent Is Nothing OrElse targetGenericDefinition.ContainingSymbol Is parent.TargetGenericDefinition)
_pairs = pairs
_parent = parent
_targetGenericDefinition = targetGenericDefinition
End Sub
''' <summary>
''' Create substitution to handle alpha-renaming of type parameters.
''' It maps type parameter definition to corresponding alpha-renamed type parameter.
''' </summary>
''' <param name="alphaRenamedTypeParameters">Alpha-renamed type parameters.</param>
Public Shared Function CreateForAlphaRename(
parent As TypeSubstitution,
alphaRenamedTypeParameters As ImmutableArray(Of SubstitutedTypeParameterSymbol)
) As TypeSubstitution
Debug.Assert(parent IsNot Nothing)
Debug.Assert(Not alphaRenamedTypeParameters.IsEmpty)
Dim memberDefinition As Symbol = alphaRenamedTypeParameters(0).OriginalDefinition.ContainingSymbol
Debug.Assert(parent.TargetGenericDefinition Is memberDefinition.ContainingSymbol)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol)
If memberDefinition.Kind = SymbolKind.Method Then
typeParametersDefinitions = DirectCast(memberDefinition, MethodSymbol).TypeParameters
Else
typeParametersDefinitions = DirectCast(memberDefinition, NamedTypeSymbol).TypeParameters
End If
Debug.Assert(Not typeParametersDefinitions.IsEmpty AndAlso
alphaRenamedTypeParameters.Length = typeParametersDefinitions.Length)
' Build complete map for memberDefinition's type parameters
Dim pairs(typeParametersDefinitions.Length - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
For i As Integer = 0 To typeParametersDefinitions.Length - 1 Step 1
Debug.Assert(Not TypeOf typeParametersDefinitions(i) Is SubstitutedTypeParameterSymbol)
Debug.Assert(alphaRenamedTypeParameters(i).OriginalDefinition Is typeParametersDefinitions(i))
pairs(i) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), New TypeWithModifiers(alphaRenamedTypeParameters(i)))
Next
Return Concat(parent, memberDefinition, pairs.AsImmutableOrNull())
End Function
''' <summary>
''' Create TypeSubstitution that can be used to substitute method's type parameters
''' in types involved in method's signature.
'''
''' Unlike for other construction methods in this class, targetMethod doesn't have to be
''' original definition, it is allowed to be specialized unconstructed generic method.
'''
''' An item in typeArguments can be an alpha-renamed type parameter, but it must belong
''' to the targetMethod and can only appear at its ordinal position to represent the lack
''' of substitution for it.
''' </summary>
Public Shared Function CreateAdditionalMethodTypeParameterSubstitution(
targetMethod As MethodSymbol,
typeArguments As ImmutableArray(Of TypeWithModifiers)
) As TypeSubstitution
Debug.Assert(targetMethod.Arity > 0 AndAlso typeArguments.Length = targetMethod.Arity AndAlso
targetMethod.ConstructedFrom Is targetMethod)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol) = targetMethod.TypeParameters
Dim argument As TypeWithModifiers
Dim countOfMeaningfulPairs As Integer = 0
For i As Integer = 0 To typeArguments.Length - 1 Step 1
argument = typeArguments(i)
If argument.Type.IsTypeParameter() Then
Dim typeParameter = DirectCast(argument.Type, TypeParameterSymbol)
If typeParameter.Ordinal = i AndAlso typeParameter.ContainingSymbol Is targetMethod Then
Debug.Assert(typeParameter Is typeParametersDefinitions(i))
If argument.CustomModifiers.IsDefaultOrEmpty Then
Continue For
End If
End If
Debug.Assert(typeParameter.IsDefinition) ' Can't be an alpha renamed type parameter.
End If
countOfMeaningfulPairs += 1
Next
If countOfMeaningfulPairs = 0 Then
'Identity substitution
Return Nothing
End If
' Build the map
Dim pairs(countOfMeaningfulPairs - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
countOfMeaningfulPairs = 0
For i As Integer = 0 To typeArguments.Length - 1 Step 1
argument = typeArguments(i)
If argument.Type.IsTypeParameter() Then
Dim typeParameter = DirectCast(argument.Type, TypeParameterSymbol)
If typeParameter.Ordinal = i AndAlso typeParameter.ContainingSymbol Is targetMethod AndAlso argument.CustomModifiers.IsDefaultOrEmpty Then
Continue For
End If
End If
pairs(countOfMeaningfulPairs) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), argument)
countOfMeaningfulPairs += 1
Next
Debug.Assert(countOfMeaningfulPairs = pairs.Length)
Return New TypeSubstitution(targetMethod, pairs.AsImmutableOrNull(), Nothing)
End Function
''' <summary>
''' Adjust substitution for construction.
''' This has the following effects:
''' 1) The passed in additionalSubstitution is used on each type argument.
''' 2) If any parameters in the given additionalSubstitution are not present in oldConstructSubstitution, they are added.
''' 3) Parent substitution in oldConstructSubstitution is replaced with adjustedParent.
'''
''' oldConstructSubstitution can be cancelled out by additionalSubstitution. In this case,
''' if the adjustedParent is Nothing, Nothing is returned.
''' </summary>
Public Shared Function AdjustForConstruct(
adjustedParent As TypeSubstitution,
oldConstructSubstitution As TypeSubstitution,
additionalSubstitution As TypeSubstitution
) As TypeSubstitution
Debug.Assert(oldConstructSubstitution IsNot Nothing AndAlso oldConstructSubstitution.TargetGenericDefinition.IsDefinition)
Debug.Assert(additionalSubstitution IsNot Nothing)
Debug.Assert(adjustedParent Is Nothing OrElse
(adjustedParent.TargetGenericDefinition.IsDefinition AndAlso
(oldConstructSubstitution.Parent Is Nothing OrElse
adjustedParent.TargetGenericDefinition Is oldConstructSubstitution.Parent.TargetGenericDefinition)))
Dim pairs = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
Dim pairsHaveChanged As Boolean = PrivateAdjustForConstruct(pairs, oldConstructSubstitution, additionalSubstitution)
Dim result As TypeSubstitution
' glue new parts together
If pairsHaveChanged OrElse oldConstructSubstitution.Parent IsNot adjustedParent Then
If pairs.Count = 0 AndAlso adjustedParent Is Nothing Then
result = Nothing
Else
result = Concat(adjustedParent,
oldConstructSubstitution.TargetGenericDefinition,
If(pairsHaveChanged, pairs.ToImmutable(), oldConstructSubstitution.Pairs))
End If
Else
result = oldConstructSubstitution
End If
pairs.Free()
Return result
End Function
''' <summary>
''' This has the following effects:
''' 1) The passed in additionalSubstitution is used on each type argument.
''' 2) If any parameters in the given additionalSubstitution are not present in oldConstructSubstitution, they are added.
'''
''' Result is placed into pairs. Identity substitutions are omitted.
'''
''' Returns True if the set of pairs have changed, False otherwise.
''' </summary>
Private Shared Function PrivateAdjustForConstruct(
pairs As ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)),
oldConstructSubstitution As TypeSubstitution,
additionalSubstitution As TypeSubstitution
) As Boolean
' Substitute into target of each existing substitution.
Dim pairsHaveChanged As Boolean = False
Dim oldPairs = oldConstructSubstitution.Pairs
Dim haveSubstitutionForOrdinal As BitVector = Nothing
Dim targetGenericDefinition As Symbol = oldConstructSubstitution.TargetGenericDefinition
If oldPairs.Length > 0 Then
Dim arity As Integer
If targetGenericDefinition.Kind = SymbolKind.Method Then
arity = DirectCast(targetGenericDefinition, MethodSymbol).Arity
Else
arity = DirectCast(targetGenericDefinition, NamedTypeSymbol).Arity
End If
haveSubstitutionForOrdinal = BitVector.Create(arity)
End If
For i = 0 To oldPairs.Length - 1 Step 1
Dim newValue As TypeWithModifiers = oldPairs(i).Value.InternalSubstituteTypeParameters(additionalSubstitution)
' Mark that we had this substitution even if it is going to disappear.
' We still don't want to append substitution for this guy from additionalSubstitution.
haveSubstitutionForOrdinal(oldPairs(i).Key.Ordinal) = True
If Not newValue.Equals(oldPairs(i).Value) Then
pairsHaveChanged = True
End If
' Do not add identity mapping.
If Not newValue.Is(oldPairs(i).Key) Then
pairs.Add(New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(oldPairs(i).Key, newValue))
End If
Next
Dim append As TypeSubstitution = additionalSubstitution.GetSubstitutionForGenericDefinition(targetGenericDefinition)
' append new pairs
If append IsNot Nothing Then
For Each additionalPair In append.Pairs
If haveSubstitutionForOrdinal.IsNull OrElse Not haveSubstitutionForOrdinal(additionalPair.Key.Ordinal) Then
pairsHaveChanged = True
pairs.Add(additionalPair)
End If
Next
End If
Return pairsHaveChanged
End Function
''' <summary>
''' Create substitution for targetGenericDefinition based on its type
''' arguments (matched to type parameters by position) and TypeSubstitution
''' for direct or indirect container.
''' </summary>
Public Shared Function Create(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
args As ImmutableArray(Of TypeWithModifiers),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Debug.Assert(parent IsNot Nothing)
Debug.Assert(targetGenericDefinition.IsDefinition)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol)
If targetGenericDefinition.Kind = SymbolKind.Method Then
typeParametersDefinitions = DirectCast(targetGenericDefinition, MethodSymbol).TypeParameters
Else
typeParametersDefinitions = DirectCast(targetGenericDefinition, NamedTypeSymbol).TypeParameters
End If
Dim n = typeParametersDefinitions.Length
Debug.Assert(n > 0)
If args.Length <> n Then
Throw New ArgumentException(VBResources.NumberOfTypeParametersAndArgumentsMustMatch)
End If
Dim significantMaps As Integer = 0
For i As Integer = 0 To n - 1 Step 1
Dim arg = args(i)
If Not arg.Is(typeParametersDefinitions(i)) Then
significantMaps += 1
End If
If Not allowAlphaRenamedTypeParametersAsArguments Then
' Can't use alpha-renamed type parameters as arguments
If arg.Type.IsTypeParameter() AndAlso Not arg.Type.IsDefinition Then
Throw New ArgumentException()
End If
End If
Next
If significantMaps = 0 Then
Return Concat(targetGenericDefinition, parent, Nothing)
End If
Dim pairIndex = 0
Dim pairs(significantMaps - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
For i As Integer = 0 To n - 1 Step 1
If Not args(i).Is(typeParametersDefinitions(i)) Then
pairs(pairIndex) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), args(i))
pairIndex += 1
End If
Next
Debug.Assert(pairIndex = significantMaps)
Return Concat(parent, targetGenericDefinition, pairs.AsImmutableOrNull())
End Function
Public Function SubstituteCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
If type.IsTypeParameter() Then
Return New TypeWithModifiers(type, customModifiers).InternalSubstituteTypeParameters(Me).CustomModifiers
End If
Return SubstituteCustomModifiers(customModifiers)
End Function
Public Function SubstituteCustomModifiers(customModifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
If customModifiers.IsDefaultOrEmpty Then
Return customModifiers
End If
For i As Integer = 0 To customModifiers.Length - 1
Dim modifier = DirectCast(customModifiers(i).Modifier, NamedTypeSymbol)
Dim substituted = DirectCast(modifier.InternalSubstituteTypeParameters(Me).AsTypeSymbolOnly(), NamedTypeSymbol)
If Not TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything) Then
Dim builder = ArrayBuilder(Of CustomModifier).GetInstance(customModifiers.Length)
builder.AddRange(customModifiers, i)
builder.Add(If(customModifiers(i).IsOptional, VisualBasicCustomModifier.CreateOptional(substituted), VisualBasicCustomModifier.CreateRequired(substituted)))
For j As Integer = i + 1 To customModifiers.Length - 1
modifier = DirectCast(customModifiers(j).Modifier, NamedTypeSymbol)
substituted = DirectCast(modifier.InternalSubstituteTypeParameters(Me).AsTypeSymbolOnly(), NamedTypeSymbol)
If Not TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything) Then
builder.Add(If(customModifiers(j).IsOptional, VisualBasicCustomModifier.CreateOptional(substituted), VisualBasicCustomModifier.CreateRequired(substituted)))
Else
builder.Add(customModifiers(j))
End If
Next
Debug.Assert(builder.Count = customModifiers.Length)
Return builder.ToImmutableAndFree()
End If
Next
Return customModifiers
End Function
Public Function WasConstructedForModifiers() As Boolean
For Each pair In _pairs
If Not pair.Key.Equals(pair.Value.Type.OriginalDefinition) Then
Return False
End If
Next
Return If(_parent Is Nothing, True, _parent.WasConstructedForModifiers())
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.Generic
Imports System.Collections.Immutable
Imports System.Runtime.InteropServices
Imports System.Text
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Immutable. Thread-safe.
'''
''' Represents a type substitution, with substitutions of types for a set of type parameters.
''' Each TypeSubstitution object has three pieces of information:
''' - OriginalDefinition of generic symbol the substitution is targeting.
''' - An array of pairs that provide a mapping from symbol's type parameters to type arguments.
''' identity substitutions are omitted.
''' - TypeSubstitution object for containing type to provide mapping for its type
''' parameters, if any.
'''
''' The identity substitution (for the whole type hierarchy) is represented by Nothing. That said,
''' top level parent of non-Nothing instance of TypeSubstitution is guaranteed to be non-identity
''' substitution. The instance may still be an identity substitution just for target generic definition,
''' which will be represented by an empty mapping array.
'''
''' The chain of TypeSubstitution objects is guaranteed to not skip any type in the containership hierarchy,
''' even types with zero arity contained in generic type will have corresponding TypeSubstitution object with
''' empty mapping array.
'''
''' Example:
''' Class A(Of T,S)
''' Class B
''' Class C(Of U)
''' End Class
''' End Class
''' End Class
'''
''' TypeSubstitution for A(Of Integer, S).B.C(Of Byte) is C{U->Byte}=>B{}=>A{T->Integer}
''' TypeSubstitution for A(Of T, S).B.C(Of Byte) is C{U->Byte}
''' TypeSubstitution for A(Of Integer, S).B is B{}=>A{T->Integer}
''' TypeSubstitution for A(Of Integer, S).B.C(Of U) is C{}=>B{}=>A{T->Integer}
'''
''' CONSIDER:
''' An array of KeyValuePair(Of TypeParameterSymbol, TypeSymbol)objects is used to represent type
''' parameter substitution mostly due to historical reasons. It might be more convenient and more
''' efficient to use ordinal based array of TypeSymbol objects instead.
'''
''' There is a Construct method that can be called on original definition with TypeSubstitution object as
''' an argument. The advantage of that method is the ability to substitute type parameters of several types
''' in the containership hierarchy in one call. What type the TypeSubstitution parameter targets makes a
''' difference.
'''
''' For example:
''' C.Construct(C{}=>B{}=>A{T->Integer}) == A(Of Integer, S).B.C(Of U)
''' C.Construct(B{}=>A{T->Integer}) == A(Of Integer, S).B.C(Of )
''' B.Construct(B{}=>A{T->Integer}) == A(Of Integer, S).B
'''
''' See comment for IsValidToApplyTo method as well.
''' </summary>
Friend Class TypeSubstitution
''' <summary>
''' A map between type parameters of _targetGenericDefinition and corresponding type arguments.
''' Represented by an array of Key-Value pairs. Keys are type parameters of _targetGenericDefinition
''' in no particular order. Identity substitutions are omitted.
''' </summary>
Private ReadOnly _pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
''' <summary>
''' Definition of a symbol which this instance of TypeSubstitution primarily targets.
''' </summary>
Private ReadOnly _targetGenericDefinition As Symbol
''' <summary>
''' An instance of TypeSubstitution describing substitution for containing type.
''' </summary>
Private ReadOnly _parent As TypeSubstitution
Public ReadOnly Property Pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
Get
Return _pairs
End Get
End Property
''' <summary>
''' Get all the pairs of substitutions, including from the parent substitutions. The substitutions
''' are in order from outside-in (parent substitutions before child substitutions).
''' </summary>
Public ReadOnly Property PairsIncludingParent As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
Get
If _parent Is Nothing Then
Return Pairs
Else
Dim pairBuilder = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
AddPairsIncludingParentToBuilder(pairBuilder)
Return pairBuilder.ToImmutableAndFree()
End If
End Get
End Property
'Add pairs (including parent pairs) to the given array builder.
Private Sub AddPairsIncludingParentToBuilder(pairBuilder As ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)))
If _parent IsNot Nothing Then
_parent.AddPairsIncludingParentToBuilder(pairBuilder)
End If
pairBuilder.AddRange(_pairs)
End Sub
Public ReadOnly Property Parent As TypeSubstitution
Get
Return _parent
End Get
End Property
Public ReadOnly Property TargetGenericDefinition As Symbol
Get
Return _targetGenericDefinition
End Get
End Property
' If this substitution contains the given type parameter, return the substituted type.
' Otherwise, returns the type parameter itself.
Public Function GetSubstitutionFor(tp As TypeParameterSymbol) As TypeWithModifiers
Debug.Assert(tp IsNot Nothing)
Debug.Assert(tp.IsDefinition OrElse TargetGenericDefinition Is tp.ContainingSymbol)
Dim containingSymbol As Symbol = tp.ContainingSymbol
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is containingSymbol Then
For Each p In current.Pairs
If p.Key.Equals(tp) Then Return p.Value
Next
' not found, return the passed in type parameters
Return New TypeWithModifiers(tp, ImmutableArray(Of CustomModifier).Empty)
End If
current = current.Parent
Loop While current IsNot Nothing
' not found, return the passed in type parameters
Return New TypeWithModifiers(tp, ImmutableArray(Of CustomModifier).Empty)
End Function
Public Function GetTypeArgumentsFor(originalDefinition As NamedTypeSymbol, <Out> ByRef hasTypeArgumentsCustomModifiers As Boolean) As ImmutableArray(Of TypeSymbol)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Dim result = ArrayBuilder(Of TypeSymbol).GetInstance(originalDefinition.Arity, fillWithValue:=Nothing)
hasTypeArgumentsCustomModifiers = False
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
result(p.Key.Ordinal) = p.Value.Type
If Not p.Value.CustomModifiers.IsDefaultOrEmpty Then
hasTypeArgumentsCustomModifiers = True
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
For i As Integer = 0 To result.Count - 1
If result(i) Is Nothing Then
result(i) = originalDefinition.TypeParameters(i)
End If
Next
Return result.ToImmutableAndFree()
End Function
Public Function GetTypeArgumentsCustomModifiersFor(originalDefinition As TypeParameterSymbol) As ImmutableArray(Of CustomModifier)
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is originalDefinition.ContainingSymbol Then
For Each p In current.Pairs
If p.Key.Ordinal = originalDefinition.Ordinal Then
Return p.Value.CustomModifiers
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
Return ImmutableArray(Of CustomModifier).Empty
End Function
Public Function HasTypeArgumentsCustomModifiersFor(originalDefinition As NamedTypeSymbol) As Boolean
Debug.Assert(originalDefinition IsNot Nothing)
Debug.Assert(originalDefinition.IsDefinition)
Debug.Assert(originalDefinition.Arity > 0)
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is originalDefinition Then
For Each p In current.Pairs
If Not p.Value.CustomModifiers.IsDefaultOrEmpty Then
Return True
End If
Next
Exit Do
End If
current = current.Parent
Loop While current IsNot Nothing
Return False
End Function
''' <summary>
''' Verify TypeSubstitution to make sure it doesn't map any
''' type parameter to an alpha-renamed type parameter.
''' </summary>
''' <remarks></remarks>
Public Sub ThrowIfSubstitutingToAlphaRenamedTypeParameter()
Dim toCheck As TypeSubstitution = Me
Do
For Each pair In toCheck.Pairs
Dim value As TypeSymbol = pair.Value.Type
If value.IsTypeParameter() AndAlso Not value.IsDefinition Then
Throw New ArgumentException()
End If
Next
toCheck = toCheck.Parent
Loop While toCheck IsNot Nothing
End Sub
''' <summary>
''' Return TypeSubstitution instance that targets particular generic definition.
''' </summary>
Public Function GetSubstitutionForGenericDefinition(
targetGenericDefinition As Symbol
) As TypeSubstitution
Dim current As TypeSubstitution = Me
Do
If current.TargetGenericDefinition Is targetGenericDefinition Then
Return current
End If
current = current.Parent
Loop While current IsNot Nothing
Return Nothing
End Function
''' <summary>
''' Return TypeSubstitution instance that targets particular
''' generic definition or one of its containers.
''' </summary>
Public Function GetSubstitutionForGenericDefinitionOrContainers(
targetGenericDefinition As Symbol
) As TypeSubstitution
Dim current As TypeSubstitution = Me
Do
If current.IsValidToApplyTo(targetGenericDefinition) Then
Return current
End If
current = current.Parent
Loop While current IsNot Nothing
Return Nothing
End Function
''' <summary>
''' Does substitution target either genericDefinition or
''' one of its containers?
''' </summary>
Public Function IsValidToApplyTo(genericDefinition As Symbol) As Boolean
Debug.Assert(genericDefinition.IsDefinition)
Dim current As Symbol = genericDefinition
Do
If current Is Me.TargetGenericDefinition Then
Return True
End If
current = current.ContainingType
Loop While current IsNot Nothing
Return False
End Function
''' <summary>
''' Combine two substitutions into one by concatenating.
'''
''' They may not directly or indirectly (through Parent) target the same generic definition.
''' sub2 is expected to target types lower in the containership hierarchy.
''' Either or both can be Nothing.
'''
''' targetGenericDefinition specifies target generic definition for the result.
''' If sub2 is not Nothing, it must target targetGenericDefinition.
''' If sub2 is Nothing, sub1 will be "extended" with identity substitutions to target
''' targetGenericDefinition.
''' </summary>
Public Shared Function Concat(targetGenericDefinition As Symbol, sub1 As TypeSubstitution, sub2 As TypeSubstitution) As TypeSubstitution
Debug.Assert(targetGenericDefinition.IsDefinition)
Debug.Assert(sub2 Is Nothing OrElse sub2.TargetGenericDefinition Is targetGenericDefinition)
If sub1 Is Nothing Then
Return sub2
Else
Debug.Assert(sub1.TargetGenericDefinition.IsDefinition)
If sub2 Is Nothing Then
If targetGenericDefinition Is sub1.TargetGenericDefinition Then
Return sub1
End If
Return Concat(sub1, targetGenericDefinition, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty)
Else
Return ConcatNotNulls(sub1, sub2)
End If
End If
End Function
Private Shared Function ConcatNotNulls(sub1 As TypeSubstitution, sub2 As TypeSubstitution) As TypeSubstitution
If sub2.Parent Is Nothing Then
Return Concat(sub1, sub2.TargetGenericDefinition, sub2.Pairs)
Else
Return Concat(ConcatNotNulls(sub1, sub2.Parent), sub2.TargetGenericDefinition, sub2.Pairs)
End If
End Function
''' <summary>
''' Create a substitution. If the substitution is the identity substitution, Nothing is returned.
''' </summary>
''' <param name="targetGenericDefinition">Generic definition the result should target.</param>
''' <param name="params">
''' Type parameter definitions. Duplicates aren't allowed. Type parameters of containing type
''' must precede type parameters of a nested type.
''' </param>
''' <param name="args">Corresponding type arguments.</param>
''' <returns></returns>
Public Shared Function Create(
targetGenericDefinition As Symbol,
params() As TypeParameterSymbol,
args() As TypeWithModifiers,
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition, params.AsImmutableOrNull, args.AsImmutableOrNull, allowAlphaRenamedTypeParametersAsArguments)
End Function
Public Shared Function Create(
targetGenericDefinition As Symbol,
params() As TypeParameterSymbol,
args() As TypeSymbol,
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition, params.AsImmutableOrNull, args.AsImmutableOrNull, allowAlphaRenamedTypeParametersAsArguments)
End Function
''' <summary>
''' Create a substitution. If the substitution is the identity substitution, Nothing is returned.
''' </summary>
''' <param name="targetGenericDefinition">Generic definition the result should target.</param>
''' <param name="params">
''' Type parameter definitions. Duplicates aren't allowed. Type parameters of containing type
''' must precede type parameters of a nested type.
''' </param>
''' <param name="args">Corresponding type arguments.</param>
''' <returns></returns>
Public Shared Function Create(
targetGenericDefinition As Symbol,
params As ImmutableArray(Of TypeParameterSymbol),
args As ImmutableArray(Of TypeWithModifiers),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Debug.Assert(targetGenericDefinition.IsDefinition)
If params.Length <> args.Length Then
Throw New ArgumentException(VBResources.NumberOfTypeParametersAndArgumentsMustMatch)
End If
Dim currentParent As TypeSubstitution = Nothing
Dim currentContainer As Symbol = Nothing
#If DEBUG Then
Dim haveSubstitutionForOrdinal = BitVector.Create(params.Length)
#End If
Dim pairs = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
Try
For i = 0 To params.Length - 1
Dim param As TypeParameterSymbol = params(i)
Dim arg As TypeWithModifiers = args(i)
Debug.Assert(param.IsDefinition)
If currentContainer IsNot param.ContainingSymbol Then
' starting new segment, finish the current one
If pairs.Count > 0 Then
currentParent = Concat(currentParent, currentContainer, pairs.ToImmutable())
pairs.Clear()
End If
currentContainer = param.ContainingSymbol
#If DEBUG Then
haveSubstitutionForOrdinal.Clear()
#End If
End If
#If DEBUG Then
Debug.Assert(Not haveSubstitutionForOrdinal(param.Ordinal))
haveSubstitutionForOrdinal(param.Ordinal) = True
#End If
If arg.Is(param) Then
Continue For
End If
If Not allowAlphaRenamedTypeParametersAsArguments Then
' Can't use alpha-renamed type parameters as arguments
If arg.Type.IsTypeParameter() AndAlso Not arg.Type.IsDefinition Then
Throw New ArgumentException()
End If
End If
pairs.Add(New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(param, arg))
Next
' finish the current segment
If pairs.Count > 0 Then
currentParent = Concat(currentParent, currentContainer, pairs.ToImmutable())
End If
Finally
pairs.Free()
End Try
If currentParent IsNot Nothing AndAlso currentParent.TargetGenericDefinition IsNot targetGenericDefinition Then
currentParent = Concat(currentParent, targetGenericDefinition, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty)
#If DEBUG Then
ElseIf currentContainer IsNot Nothing AndAlso currentContainer IsNot targetGenericDefinition Then
' currentContainer must be either targetGenericDefinition or a container of targetGenericDefinition
Dim container As NamedTypeSymbol = targetGenericDefinition.ContainingType
While container IsNot Nothing AndAlso container IsNot currentContainer
container = container.ContainingType
End While
Debug.Assert(container Is currentContainer)
#End If
End If
Return currentParent
End Function
Private Shared ReadOnly s_withoutModifiers As Func(Of TypeSymbol, TypeWithModifiers) = Function(arg) New TypeWithModifiers(arg)
Public Shared Function Create(
targetGenericDefinition As Symbol,
params As ImmutableArray(Of TypeParameterSymbol),
args As ImmutableArray(Of TypeSymbol),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(targetGenericDefinition,
params,
args.SelectAsArray(s_withoutModifiers),
allowAlphaRenamedTypeParametersAsArguments)
End Function
Public Shared Function Create(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
args As ImmutableArray(Of TypeSymbol),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Return Create(parent,
targetGenericDefinition,
args.SelectAsArray(s_withoutModifiers),
allowAlphaRenamedTypeParametersAsArguments)
End Function
''' <summary>
''' Private helper to make sure identity substitutions are injected for types between
''' targetGenericDefinition and parent.TargetGenericDefinition.
''' </summary>
Private Shared Function Concat(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers))
) As TypeSubstitution
If parent Is Nothing OrElse parent.TargetGenericDefinition Is targetGenericDefinition.ContainingType Then
Return New TypeSubstitution(targetGenericDefinition, pairs, parent)
End If
Dim containingType As NamedTypeSymbol = targetGenericDefinition.ContainingType
Debug.Assert(containingType IsNot Nothing)
Return New TypeSubstitution(
targetGenericDefinition,
pairs,
Concat(parent, containingType, ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).Empty))
End Function
Public Overrides Function ToString() As String
Dim builder As New StringBuilder()
builder.AppendFormat("{0} : ", TargetGenericDefinition)
ToString(builder)
Return builder.ToString()
End Function
Private Overloads Sub ToString(builder As StringBuilder)
If _parent IsNot Nothing Then
_parent.ToString(builder)
builder.Append(", ")
End If
builder.Append("{"c)
For i = 0 To _pairs.Length - 1
If i <> 0 Then
builder.Append(", ")
End If
builder.AppendFormat("{0}->{1}", _pairs(i).Key.ToString(), _pairs(i).Value.Type.ToString())
Next
builder.Append("}"c)
End Sub
Private Sub New(targetGenericDefinition As Symbol, pairs As ImmutableArray(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)), parent As TypeSubstitution)
Debug.Assert(Not pairs.IsDefault)
Debug.Assert(pairs.All(Function(p) p.Key IsNot Nothing))
Debug.Assert(pairs.All(Function(p) p.Value.Type IsNot Nothing))
Debug.Assert(pairs.All(Function(p) Not p.Value.CustomModifiers.IsDefault))
Debug.Assert(targetGenericDefinition IsNot Nothing AndAlso
(targetGenericDefinition.IsDefinition OrElse
(targetGenericDefinition.Kind = SymbolKind.Method AndAlso
DirectCast(targetGenericDefinition, MethodSymbol).ConstructedFrom Is targetGenericDefinition AndAlso
parent Is Nothing)))
Debug.Assert((targetGenericDefinition.Kind = SymbolKind.Method AndAlso
(DirectCast(targetGenericDefinition, MethodSymbol).IsGenericMethod OrElse
(targetGenericDefinition.ContainingType.IsOrInGenericType() AndAlso parent IsNot Nothing))) OrElse
((targetGenericDefinition.Kind = SymbolKind.NamedType OrElse targetGenericDefinition.Kind = SymbolKind.ErrorType) AndAlso
DirectCast(targetGenericDefinition, NamedTypeSymbol).IsOrInGenericType()))
Debug.Assert(parent Is Nothing OrElse targetGenericDefinition.ContainingSymbol Is parent.TargetGenericDefinition)
_pairs = pairs
_parent = parent
_targetGenericDefinition = targetGenericDefinition
End Sub
''' <summary>
''' Create substitution to handle alpha-renaming of type parameters.
''' It maps type parameter definition to corresponding alpha-renamed type parameter.
''' </summary>
''' <param name="alphaRenamedTypeParameters">Alpha-renamed type parameters.</param>
Public Shared Function CreateForAlphaRename(
parent As TypeSubstitution,
alphaRenamedTypeParameters As ImmutableArray(Of SubstitutedTypeParameterSymbol)
) As TypeSubstitution
Debug.Assert(parent IsNot Nothing)
Debug.Assert(Not alphaRenamedTypeParameters.IsEmpty)
Dim memberDefinition As Symbol = alphaRenamedTypeParameters(0).OriginalDefinition.ContainingSymbol
Debug.Assert(parent.TargetGenericDefinition Is memberDefinition.ContainingSymbol)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol)
If memberDefinition.Kind = SymbolKind.Method Then
typeParametersDefinitions = DirectCast(memberDefinition, MethodSymbol).TypeParameters
Else
typeParametersDefinitions = DirectCast(memberDefinition, NamedTypeSymbol).TypeParameters
End If
Debug.Assert(Not typeParametersDefinitions.IsEmpty AndAlso
alphaRenamedTypeParameters.Length = typeParametersDefinitions.Length)
' Build complete map for memberDefinition's type parameters
Dim pairs(typeParametersDefinitions.Length - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
For i As Integer = 0 To typeParametersDefinitions.Length - 1 Step 1
Debug.Assert(Not TypeOf typeParametersDefinitions(i) Is SubstitutedTypeParameterSymbol)
Debug.Assert(alphaRenamedTypeParameters(i).OriginalDefinition Is typeParametersDefinitions(i))
pairs(i) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), New TypeWithModifiers(alphaRenamedTypeParameters(i)))
Next
Return Concat(parent, memberDefinition, pairs.AsImmutableOrNull())
End Function
''' <summary>
''' Create TypeSubstitution that can be used to substitute method's type parameters
''' in types involved in method's signature.
'''
''' Unlike for other construction methods in this class, targetMethod doesn't have to be
''' original definition, it is allowed to be specialized unconstructed generic method.
'''
''' An item in typeArguments can be an alpha-renamed type parameter, but it must belong
''' to the targetMethod and can only appear at its ordinal position to represent the lack
''' of substitution for it.
''' </summary>
Public Shared Function CreateAdditionalMethodTypeParameterSubstitution(
targetMethod As MethodSymbol,
typeArguments As ImmutableArray(Of TypeWithModifiers)
) As TypeSubstitution
Debug.Assert(targetMethod.Arity > 0 AndAlso typeArguments.Length = targetMethod.Arity AndAlso
targetMethod.ConstructedFrom Is targetMethod)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol) = targetMethod.TypeParameters
Dim argument As TypeWithModifiers
Dim countOfMeaningfulPairs As Integer = 0
For i As Integer = 0 To typeArguments.Length - 1 Step 1
argument = typeArguments(i)
If argument.Type.IsTypeParameter() Then
Dim typeParameter = DirectCast(argument.Type, TypeParameterSymbol)
If typeParameter.Ordinal = i AndAlso typeParameter.ContainingSymbol Is targetMethod Then
Debug.Assert(typeParameter Is typeParametersDefinitions(i))
If argument.CustomModifiers.IsDefaultOrEmpty Then
Continue For
End If
End If
Debug.Assert(typeParameter.IsDefinition) ' Can't be an alpha renamed type parameter.
End If
countOfMeaningfulPairs += 1
Next
If countOfMeaningfulPairs = 0 Then
'Identity substitution
Return Nothing
End If
' Build the map
Dim pairs(countOfMeaningfulPairs - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
countOfMeaningfulPairs = 0
For i As Integer = 0 To typeArguments.Length - 1 Step 1
argument = typeArguments(i)
If argument.Type.IsTypeParameter() Then
Dim typeParameter = DirectCast(argument.Type, TypeParameterSymbol)
If typeParameter.Ordinal = i AndAlso typeParameter.ContainingSymbol Is targetMethod AndAlso argument.CustomModifiers.IsDefaultOrEmpty Then
Continue For
End If
End If
pairs(countOfMeaningfulPairs) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), argument)
countOfMeaningfulPairs += 1
Next
Debug.Assert(countOfMeaningfulPairs = pairs.Length)
Return New TypeSubstitution(targetMethod, pairs.AsImmutableOrNull(), Nothing)
End Function
''' <summary>
''' Adjust substitution for construction.
''' This has the following effects:
''' 1) The passed in additionalSubstitution is used on each type argument.
''' 2) If any parameters in the given additionalSubstitution are not present in oldConstructSubstitution, they are added.
''' 3) Parent substitution in oldConstructSubstitution is replaced with adjustedParent.
'''
''' oldConstructSubstitution can be cancelled out by additionalSubstitution. In this case,
''' if the adjustedParent is Nothing, Nothing is returned.
''' </summary>
Public Shared Function AdjustForConstruct(
adjustedParent As TypeSubstitution,
oldConstructSubstitution As TypeSubstitution,
additionalSubstitution As TypeSubstitution
) As TypeSubstitution
Debug.Assert(oldConstructSubstitution IsNot Nothing AndAlso oldConstructSubstitution.TargetGenericDefinition.IsDefinition)
Debug.Assert(additionalSubstitution IsNot Nothing)
Debug.Assert(adjustedParent Is Nothing OrElse
(adjustedParent.TargetGenericDefinition.IsDefinition AndAlso
(oldConstructSubstitution.Parent Is Nothing OrElse
adjustedParent.TargetGenericDefinition Is oldConstructSubstitution.Parent.TargetGenericDefinition)))
Dim pairs = ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)).GetInstance()
Dim pairsHaveChanged As Boolean = PrivateAdjustForConstruct(pairs, oldConstructSubstitution, additionalSubstitution)
Dim result As TypeSubstitution
' glue new parts together
If pairsHaveChanged OrElse oldConstructSubstitution.Parent IsNot adjustedParent Then
If pairs.Count = 0 AndAlso adjustedParent Is Nothing Then
result = Nothing
Else
result = Concat(adjustedParent,
oldConstructSubstitution.TargetGenericDefinition,
If(pairsHaveChanged, pairs.ToImmutable(), oldConstructSubstitution.Pairs))
End If
Else
result = oldConstructSubstitution
End If
pairs.Free()
Return result
End Function
''' <summary>
''' This has the following effects:
''' 1) The passed in additionalSubstitution is used on each type argument.
''' 2) If any parameters in the given additionalSubstitution are not present in oldConstructSubstitution, they are added.
'''
''' Result is placed into pairs. Identity substitutions are omitted.
'''
''' Returns True if the set of pairs have changed, False otherwise.
''' </summary>
Private Shared Function PrivateAdjustForConstruct(
pairs As ArrayBuilder(Of KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)),
oldConstructSubstitution As TypeSubstitution,
additionalSubstitution As TypeSubstitution
) As Boolean
' Substitute into target of each existing substitution.
Dim pairsHaveChanged As Boolean = False
Dim oldPairs = oldConstructSubstitution.Pairs
Dim haveSubstitutionForOrdinal As BitVector = Nothing
Dim targetGenericDefinition As Symbol = oldConstructSubstitution.TargetGenericDefinition
If oldPairs.Length > 0 Then
Dim arity As Integer
If targetGenericDefinition.Kind = SymbolKind.Method Then
arity = DirectCast(targetGenericDefinition, MethodSymbol).Arity
Else
arity = DirectCast(targetGenericDefinition, NamedTypeSymbol).Arity
End If
haveSubstitutionForOrdinal = BitVector.Create(arity)
End If
For i = 0 To oldPairs.Length - 1 Step 1
Dim newValue As TypeWithModifiers = oldPairs(i).Value.InternalSubstituteTypeParameters(additionalSubstitution)
' Mark that we had this substitution even if it is going to disappear.
' We still don't want to append substitution for this guy from additionalSubstitution.
haveSubstitutionForOrdinal(oldPairs(i).Key.Ordinal) = True
If Not newValue.Equals(oldPairs(i).Value) Then
pairsHaveChanged = True
End If
' Do not add identity mapping.
If Not newValue.Is(oldPairs(i).Key) Then
pairs.Add(New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(oldPairs(i).Key, newValue))
End If
Next
Dim append As TypeSubstitution = additionalSubstitution.GetSubstitutionForGenericDefinition(targetGenericDefinition)
' append new pairs
If append IsNot Nothing Then
For Each additionalPair In append.Pairs
If haveSubstitutionForOrdinal.IsNull OrElse Not haveSubstitutionForOrdinal(additionalPair.Key.Ordinal) Then
pairsHaveChanged = True
pairs.Add(additionalPair)
End If
Next
End If
Return pairsHaveChanged
End Function
''' <summary>
''' Create substitution for targetGenericDefinition based on its type
''' arguments (matched to type parameters by position) and TypeSubstitution
''' for direct or indirect container.
''' </summary>
Public Shared Function Create(
parent As TypeSubstitution,
targetGenericDefinition As Symbol,
args As ImmutableArray(Of TypeWithModifiers),
Optional allowAlphaRenamedTypeParametersAsArguments As Boolean = False
) As TypeSubstitution
Debug.Assert(parent IsNot Nothing)
Debug.Assert(targetGenericDefinition.IsDefinition)
Dim typeParametersDefinitions As ImmutableArray(Of TypeParameterSymbol)
If targetGenericDefinition.Kind = SymbolKind.Method Then
typeParametersDefinitions = DirectCast(targetGenericDefinition, MethodSymbol).TypeParameters
Else
typeParametersDefinitions = DirectCast(targetGenericDefinition, NamedTypeSymbol).TypeParameters
End If
Dim n = typeParametersDefinitions.Length
Debug.Assert(n > 0)
If args.Length <> n Then
Throw New ArgumentException(VBResources.NumberOfTypeParametersAndArgumentsMustMatch)
End If
Dim significantMaps As Integer = 0
For i As Integer = 0 To n - 1 Step 1
Dim arg = args(i)
If Not arg.Is(typeParametersDefinitions(i)) Then
significantMaps += 1
End If
If Not allowAlphaRenamedTypeParametersAsArguments Then
' Can't use alpha-renamed type parameters as arguments
If arg.Type.IsTypeParameter() AndAlso Not arg.Type.IsDefinition Then
Throw New ArgumentException()
End If
End If
Next
If significantMaps = 0 Then
Return Concat(targetGenericDefinition, parent, Nothing)
End If
Dim pairIndex = 0
Dim pairs(significantMaps - 1) As KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)
For i As Integer = 0 To n - 1 Step 1
If Not args(i).Is(typeParametersDefinitions(i)) Then
pairs(pairIndex) = New KeyValuePair(Of TypeParameterSymbol, TypeWithModifiers)(typeParametersDefinitions(i), args(i))
pairIndex += 1
End If
Next
Debug.Assert(pairIndex = significantMaps)
Return Concat(parent, targetGenericDefinition, pairs.AsImmutableOrNull())
End Function
Public Function SubstituteCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
If type.IsTypeParameter() Then
Return New TypeWithModifiers(type, customModifiers).InternalSubstituteTypeParameters(Me).CustomModifiers
End If
Return SubstituteCustomModifiers(customModifiers)
End Function
Public Function SubstituteCustomModifiers(customModifiers As ImmutableArray(Of CustomModifier)) As ImmutableArray(Of CustomModifier)
If customModifiers.IsDefaultOrEmpty Then
Return customModifiers
End If
For i As Integer = 0 To customModifiers.Length - 1
Dim modifier = DirectCast(customModifiers(i).Modifier, NamedTypeSymbol)
Dim substituted = DirectCast(modifier.InternalSubstituteTypeParameters(Me).AsTypeSymbolOnly(), NamedTypeSymbol)
If Not TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything) Then
Dim builder = ArrayBuilder(Of CustomModifier).GetInstance(customModifiers.Length)
builder.AddRange(customModifiers, i)
builder.Add(If(customModifiers(i).IsOptional, VisualBasicCustomModifier.CreateOptional(substituted), VisualBasicCustomModifier.CreateRequired(substituted)))
For j As Integer = i + 1 To customModifiers.Length - 1
modifier = DirectCast(customModifiers(j).Modifier, NamedTypeSymbol)
substituted = DirectCast(modifier.InternalSubstituteTypeParameters(Me).AsTypeSymbolOnly(), NamedTypeSymbol)
If Not TypeSymbol.Equals(modifier, substituted, TypeCompareKind.ConsiderEverything) Then
builder.Add(If(customModifiers(j).IsOptional, VisualBasicCustomModifier.CreateOptional(substituted), VisualBasicCustomModifier.CreateRequired(substituted)))
Else
builder.Add(customModifiers(j))
End If
Next
Debug.Assert(builder.Count = customModifiers.Length)
Return builder.ToImmutableAndFree()
End If
Next
Return customModifiers
End Function
Public Function WasConstructedForModifiers() As Boolean
For Each pair In _pairs
If Not pair.Key.Equals(pair.Value.Type.OriginalDefinition) Then
Return False
End If
Next
Return If(_parent Is Nothing, True, _parent.WasConstructedForModifiers())
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/VisualBasic/Portable/Parser/BlockContexts/CompilationUnitContext.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.PooledObjects
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the DeclarationContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend NotInheritable Class CompilationUnitContext
Inherits NamespaceBlockContext
Private _optionStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)
Private _importsStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)
Private _attributeStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)
Private _state As SyntaxKind
Friend Sub New(parser As Parser)
MyBase.New(SyntaxKind.CompilationUnit, Nothing, Nothing)
Me.Parser = parser
_statements = _parser._pool.Allocate(Of StatementSyntax)()
_state = SyntaxKind.OptionStatement
End Sub
Friend Overrides ReadOnly Property IsWithinAsyncMethodOrLambda As Boolean
Get
Return Parser.IsScript
End Get
End Property
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
Do
Select Case _state
Case SyntaxKind.OptionStatement
If node.Kind = SyntaxKind.OptionStatement Then
Add(node)
Return Me
End If
_optionStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)(Body.Node)
_state = SyntaxKind.ImportsStatement
Case SyntaxKind.ImportsStatement
If node.Kind = SyntaxKind.ImportsStatement Then
Add(node)
Return Me
End If
_importsStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)(Body.Node)
_state = SyntaxKind.AttributesStatement
Case SyntaxKind.AttributesStatement
If node.Kind = SyntaxKind.AttributesStatement Then
Add(node)
Return Me
End If
_attributeStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)(Body.Node)
_state = SyntaxKind.None
Case Else
' only allow executable statements in top-level script code
If _parser.IsScript Then
Dim newContext = TryProcessExecutableStatement(node)
If newContext IsNot Nothing Then
Return newContext
End If
End If
Return MyBase.ProcessSyntax(node)
End Select
Loop
End Function
Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult
If _parser.IsScript Then
Return TryLinkStatement(node, newContext)
Else
Return MyBase.TryLinkSyntax(node, newContext)
End If
End Function
Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode
Throw ExceptionUtilities.Unreachable
End Function
Friend Function CreateCompilationUnit(optionalTerminator As PunctuationSyntax,
notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax),
notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax),
haveRegionDirectives As Boolean,
notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As CompilationUnitSyntax
Debug.Assert(optionalTerminator Is Nothing OrElse optionalTerminator.Kind = SyntaxKind.EndOfFileToken)
If _state <> SyntaxKind.None Then
Select Case _state
Case SyntaxKind.OptionStatement
_optionStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)(Body.Node)
Case SyntaxKind.ImportsStatement
_importsStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)(Body.Node)
Case SyntaxKind.AttributesStatement
_attributeStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)(Body.Node)
End Select
_state = SyntaxKind.None
End If
Dim declarations = Body()
Dim result = SyntaxFactory.CompilationUnit(_optionStmts,
_importsStmts,
_attributeStmts,
declarations,
optionalTerminator)
Dim regionsAreAllowedEverywhere = Not haveRegionDirectives OrElse Parser.CheckFeatureAvailability(Feature.RegionsEverywhere)
If notClosedIfDirectives IsNot Nothing OrElse notClosedRegionDirectives IsNot Nothing OrElse notClosedExternalSourceDirective IsNot Nothing OrElse
Not regionsAreAllowedEverywhere Then
result = DiagnosticRewriter.Rewrite(result, notClosedIfDirectives, notClosedRegionDirectives, regionsAreAllowedEverywhere, notClosedExternalSourceDirective, Parser)
If notClosedIfDirectives IsNot Nothing Then
notClosedIfDirectives.Free()
End If
If notClosedRegionDirectives IsNot Nothing Then
notClosedRegionDirectives.Free()
End If
End If
FreeStatements()
Return result
End Function
Private Class DiagnosticRewriter
Inherits VisualBasicSyntaxRewriter
Private _notClosedIfDirectives As HashSet(Of IfDirectiveTriviaSyntax) = Nothing
Private _notClosedRegionDirectives As HashSet(Of RegionDirectiveTriviaSyntax) = Nothing
Private _notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax = Nothing
Private _regionsAreAllowedEverywhere As Boolean
Private _parser As Parser
Private _declarationBlocksBeingVisited As ArrayBuilder(Of VisualBasicSyntaxNode) ' CompilationUnitSyntax is treated as a declaration block for our purposes
Private _parentsOfRegionDirectivesAwaitingClosure As ArrayBuilder(Of VisualBasicSyntaxNode) ' Nodes are coming from _declarationBlocksBeingVisited
Private _tokenWithDirectivesBeingVisited As SyntaxToken
Private Sub New()
MyBase.New()
End Sub
Public Shared Function Rewrite(compilationUnit As CompilationUnitSyntax,
notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax),
notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax),
regionsAreAllowedEverywhere As Boolean,
notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax,
parser As Parser) As CompilationUnitSyntax
Dim rewriter As New DiagnosticRewriter()
If notClosedIfDirectives IsNot Nothing Then
rewriter._notClosedIfDirectives =
New HashSet(Of IfDirectiveTriviaSyntax)(ReferenceEqualityComparer.Instance)
For Each node In notClosedIfDirectives
rewriter._notClosedIfDirectives.Add(node)
Next
End If
If notClosedRegionDirectives IsNot Nothing Then
rewriter._notClosedRegionDirectives =
New HashSet(Of RegionDirectiveTriviaSyntax)(ReferenceEqualityComparer.Instance)
For Each node In notClosedRegionDirectives
rewriter._notClosedRegionDirectives.Add(node)
Next
End If
rewriter._parser = parser
rewriter._regionsAreAllowedEverywhere = regionsAreAllowedEverywhere
If Not regionsAreAllowedEverywhere Then
rewriter._declarationBlocksBeingVisited = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
rewriter._parentsOfRegionDirectivesAwaitingClosure = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
End If
rewriter._notClosedExternalSourceDirective = notClosedExternalSourceDirective
Dim result = DirectCast(rewriter.Visit(compilationUnit), CompilationUnitSyntax)
If Not regionsAreAllowedEverywhere Then
Debug.Assert(rewriter._declarationBlocksBeingVisited.Count = 0)
Debug.Assert(rewriter._parentsOfRegionDirectivesAwaitingClosure.Count = 0) ' We never add parents of not closed #Region directives into this stack.
rewriter._declarationBlocksBeingVisited.Free()
rewriter._parentsOfRegionDirectivesAwaitingClosure.Free()
End If
Return result
End Function
#If DEBUG Then
' NOTE: the logic is heavily relying on the fact that green nodes in
' NOTE: one single tree are not reused, the following code assert this
Private ReadOnly _processedNodesWithoutDuplication As HashSet(Of VisualBasicSyntaxNode) = New HashSet(Of VisualBasicSyntaxNode)(ReferenceEqualityComparer.Instance)
#End If
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitCompilationUnit(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitMethodBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitConstructorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitOperatorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitAccessorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitNamespaceBlock(node As NamespaceBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitNamespaceBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitClassBlock(node As ClassBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitClassBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitStructureBlock(node As StructureBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitStructureBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitModuleBlock(node As ModuleBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitModuleBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitInterfaceBlock(node As InterfaceBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitInterfaceBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitEnumBlock(node As EnumBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitEnumBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitPropertyBlock(node As PropertyBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitPropertyBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitEventBlock(node As EventBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitEventBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitIfDirectiveTrivia(node)
If Me._notClosedIfDirectives IsNot Nothing AndAlso Me._notClosedIfDirectives.Contains(node) Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_LbExpectedEndIf)
End If
Return rewritten
End Function
Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitRegionDirectiveTrivia(node)
If Me._notClosedRegionDirectives IsNot Nothing AndAlso Me._notClosedRegionDirectives.Contains(node) Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_ExpectedEndRegion)
ElseIf Not _regionsAreAllowedEverywhere
rewritten = VerifyRegionPlacement(node, rewritten)
End If
Return rewritten
End Function
Private Function VerifyRegionPlacement(original As VisualBasicSyntaxNode, rewritten As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
Dim containingBlock = _declarationBlocksBeingVisited.Peek()
' Ensure that the directive is inside the block, rather than is attached to it as a leading/trailing trivia
Debug.Assert(_declarationBlocksBeingVisited.Count > 1 OrElse containingBlock.Kind = SyntaxKind.CompilationUnit)
If _declarationBlocksBeingVisited.Count > 1 Then
If _tokenWithDirectivesBeingVisited Is containingBlock.GetFirstToken() Then
Dim leadingTrivia = _tokenWithDirectivesBeingVisited.GetLeadingTrivia()
If leadingTrivia IsNot Nothing AndAlso New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia).Nodes.Contains(original) Then
containingBlock = _declarationBlocksBeingVisited(_declarationBlocksBeingVisited.Count - 2)
End If
ElseIf _tokenWithDirectivesBeingVisited Is containingBlock.GetLastToken() Then
Dim trailingTrivia = _tokenWithDirectivesBeingVisited.GetTrailingTrivia()
If trailingTrivia IsNot Nothing AndAlso New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia).Nodes.Contains(original) Then
containingBlock = _declarationBlocksBeingVisited(_declarationBlocksBeingVisited.Count - 2)
End If
End If
End If
Dim reportAnError = Not IsValidContainingBlockForRegionInVB12(containingBlock)
If original.Kind = SyntaxKind.RegionDirectiveTrivia Then
_parentsOfRegionDirectivesAwaitingClosure.Push(containingBlock)
Else
Debug.Assert(original.Kind = SyntaxKind.EndRegionDirectiveTrivia)
If _parentsOfRegionDirectivesAwaitingClosure.Count > 0 Then
Dim regionBeginContainingBlock = _parentsOfRegionDirectivesAwaitingClosure.Pop()
If regionBeginContainingBlock IsNot containingBlock AndAlso IsValidContainingBlockForRegionInVB12(regionBeginContainingBlock) Then
reportAnError = True
End If
End If
End If
If reportAnError Then
rewritten = _parser.ReportFeatureUnavailable(Feature.RegionsEverywhere, rewritten)
End If
Return rewritten
End Function
Private Shared Function IsValidContainingBlockForRegionInVB12(containingBlock As VisualBasicSyntaxNode) As Boolean
Select Case containingBlock.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return False
End Select
Return True
End Function
Public Overrides Function VisitEndRegionDirectiveTrivia(node As EndRegionDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitEndRegionDirectiveTrivia(node)
If Not _regionsAreAllowedEverywhere Then
rewritten = VerifyRegionPlacement(node, rewritten)
End If
Return rewritten
End Function
Public Overrides Function VisitExternalSourceDirectiveTrivia(node As ExternalSourceDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitExternalSourceDirectiveTrivia(node)
If Me._notClosedExternalSourceDirective Is node Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_ExpectedEndExternalSource)
End If
Return rewritten
End Function
Public Overrides Function Visit(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
If node Is Nothing OrElse Not node.ContainsDirectives Then
Return node
End If
Return node.Accept(Me)
End Function
Public Overrides Function VisitSyntaxToken(token As SyntaxToken) As SyntaxToken
If token Is Nothing OrElse Not token.ContainsDirectives Then
Return token
End If
Debug.Assert(_tokenWithDirectivesBeingVisited Is Nothing)
_tokenWithDirectivesBeingVisited = token
Dim leadingTrivia = token.GetLeadingTrivia()
Dim trailingTrivia = token.GetTrailingTrivia()
If leadingTrivia IsNot Nothing Then
Dim rewritten = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia)).Node
If leadingTrivia IsNot rewritten Then
token = DirectCast(token.WithLeadingTrivia(rewritten), SyntaxToken)
End If
End If
If trailingTrivia IsNot Nothing Then
Dim rewritten = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia)).Node
If trailingTrivia IsNot rewritten Then
token = DirectCast(token.WithTrailingTrivia(rewritten), SyntaxToken)
End If
End If
_tokenWithDirectivesBeingVisited = Nothing
Return token
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Syntax.InternalSyntax
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
'-----------------------------------------------------------------------------
' Contains the definition of the DeclarationContext
'-----------------------------------------------------------------------------
Namespace Microsoft.CodeAnalysis.VisualBasic.Syntax.InternalSyntax
Friend NotInheritable Class CompilationUnitContext
Inherits NamespaceBlockContext
Private _optionStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)
Private _importsStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)
Private _attributeStmts As CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)
Private _state As SyntaxKind
Friend Sub New(parser As Parser)
MyBase.New(SyntaxKind.CompilationUnit, Nothing, Nothing)
Me.Parser = parser
_statements = _parser._pool.Allocate(Of StatementSyntax)()
_state = SyntaxKind.OptionStatement
End Sub
Friend Overrides ReadOnly Property IsWithinAsyncMethodOrLambda As Boolean
Get
Return Parser.IsScript
End Get
End Property
Friend Overrides Function ProcessSyntax(node As VisualBasicSyntaxNode) As BlockContext
Do
Select Case _state
Case SyntaxKind.OptionStatement
If node.Kind = SyntaxKind.OptionStatement Then
Add(node)
Return Me
End If
_optionStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)(Body.Node)
_state = SyntaxKind.ImportsStatement
Case SyntaxKind.ImportsStatement
If node.Kind = SyntaxKind.ImportsStatement Then
Add(node)
Return Me
End If
_importsStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)(Body.Node)
_state = SyntaxKind.AttributesStatement
Case SyntaxKind.AttributesStatement
If node.Kind = SyntaxKind.AttributesStatement Then
Add(node)
Return Me
End If
_attributeStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)(Body.Node)
_state = SyntaxKind.None
Case Else
' only allow executable statements in top-level script code
If _parser.IsScript Then
Dim newContext = TryProcessExecutableStatement(node)
If newContext IsNot Nothing Then
Return newContext
End If
End If
Return MyBase.ProcessSyntax(node)
End Select
Loop
End Function
Friend Overrides Function TryLinkSyntax(node As VisualBasicSyntaxNode, ByRef newContext As BlockContext) As LinkResult
If _parser.IsScript Then
Return TryLinkStatement(node, newContext)
Else
Return MyBase.TryLinkSyntax(node, newContext)
End If
End Function
Friend Overrides Function CreateBlockSyntax(endStmt As StatementSyntax) As VisualBasicSyntaxNode
Throw ExceptionUtilities.Unreachable
End Function
Friend Function CreateCompilationUnit(optionalTerminator As PunctuationSyntax,
notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax),
notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax),
haveRegionDirectives As Boolean,
notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax) As CompilationUnitSyntax
Debug.Assert(optionalTerminator Is Nothing OrElse optionalTerminator.Kind = SyntaxKind.EndOfFileToken)
If _state <> SyntaxKind.None Then
Select Case _state
Case SyntaxKind.OptionStatement
_optionStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of OptionStatementSyntax)(Body.Node)
Case SyntaxKind.ImportsStatement
_importsStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of ImportsStatementSyntax)(Body.Node)
Case SyntaxKind.AttributesStatement
_attributeStmts = New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of AttributesStatementSyntax)(Body.Node)
End Select
_state = SyntaxKind.None
End If
Dim declarations = Body()
Dim result = SyntaxFactory.CompilationUnit(_optionStmts,
_importsStmts,
_attributeStmts,
declarations,
optionalTerminator)
Dim regionsAreAllowedEverywhere = Not haveRegionDirectives OrElse Parser.CheckFeatureAvailability(Feature.RegionsEverywhere)
If notClosedIfDirectives IsNot Nothing OrElse notClosedRegionDirectives IsNot Nothing OrElse notClosedExternalSourceDirective IsNot Nothing OrElse
Not regionsAreAllowedEverywhere Then
result = DiagnosticRewriter.Rewrite(result, notClosedIfDirectives, notClosedRegionDirectives, regionsAreAllowedEverywhere, notClosedExternalSourceDirective, Parser)
If notClosedIfDirectives IsNot Nothing Then
notClosedIfDirectives.Free()
End If
If notClosedRegionDirectives IsNot Nothing Then
notClosedRegionDirectives.Free()
End If
End If
FreeStatements()
Return result
End Function
Private Class DiagnosticRewriter
Inherits VisualBasicSyntaxRewriter
Private _notClosedIfDirectives As HashSet(Of IfDirectiveTriviaSyntax) = Nothing
Private _notClosedRegionDirectives As HashSet(Of RegionDirectiveTriviaSyntax) = Nothing
Private _notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax = Nothing
Private _regionsAreAllowedEverywhere As Boolean
Private _parser As Parser
Private _declarationBlocksBeingVisited As ArrayBuilder(Of VisualBasicSyntaxNode) ' CompilationUnitSyntax is treated as a declaration block for our purposes
Private _parentsOfRegionDirectivesAwaitingClosure As ArrayBuilder(Of VisualBasicSyntaxNode) ' Nodes are coming from _declarationBlocksBeingVisited
Private _tokenWithDirectivesBeingVisited As SyntaxToken
Private Sub New()
MyBase.New()
End Sub
Public Shared Function Rewrite(compilationUnit As CompilationUnitSyntax,
notClosedIfDirectives As ArrayBuilder(Of IfDirectiveTriviaSyntax),
notClosedRegionDirectives As ArrayBuilder(Of RegionDirectiveTriviaSyntax),
regionsAreAllowedEverywhere As Boolean,
notClosedExternalSourceDirective As ExternalSourceDirectiveTriviaSyntax,
parser As Parser) As CompilationUnitSyntax
Dim rewriter As New DiagnosticRewriter()
If notClosedIfDirectives IsNot Nothing Then
rewriter._notClosedIfDirectives =
New HashSet(Of IfDirectiveTriviaSyntax)(ReferenceEqualityComparer.Instance)
For Each node In notClosedIfDirectives
rewriter._notClosedIfDirectives.Add(node)
Next
End If
If notClosedRegionDirectives IsNot Nothing Then
rewriter._notClosedRegionDirectives =
New HashSet(Of RegionDirectiveTriviaSyntax)(ReferenceEqualityComparer.Instance)
For Each node In notClosedRegionDirectives
rewriter._notClosedRegionDirectives.Add(node)
Next
End If
rewriter._parser = parser
rewriter._regionsAreAllowedEverywhere = regionsAreAllowedEverywhere
If Not regionsAreAllowedEverywhere Then
rewriter._declarationBlocksBeingVisited = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
rewriter._parentsOfRegionDirectivesAwaitingClosure = ArrayBuilder(Of VisualBasicSyntaxNode).GetInstance()
End If
rewriter._notClosedExternalSourceDirective = notClosedExternalSourceDirective
Dim result = DirectCast(rewriter.Visit(compilationUnit), CompilationUnitSyntax)
If Not regionsAreAllowedEverywhere Then
Debug.Assert(rewriter._declarationBlocksBeingVisited.Count = 0)
Debug.Assert(rewriter._parentsOfRegionDirectivesAwaitingClosure.Count = 0) ' We never add parents of not closed #Region directives into this stack.
rewriter._declarationBlocksBeingVisited.Free()
rewriter._parentsOfRegionDirectivesAwaitingClosure.Free()
End If
Return result
End Function
#If DEBUG Then
' NOTE: the logic is heavily relying on the fact that green nodes in
' NOTE: one single tree are not reused, the following code assert this
Private ReadOnly _processedNodesWithoutDuplication As HashSet(Of VisualBasicSyntaxNode) = New HashSet(Of VisualBasicSyntaxNode)(ReferenceEqualityComparer.Instance)
#End If
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitCompilationUnit(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitMethodBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitConstructorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitOperatorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitAccessorBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitNamespaceBlock(node As NamespaceBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitNamespaceBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitClassBlock(node As ClassBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitClassBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitStructureBlock(node As StructureBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitStructureBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitModuleBlock(node As ModuleBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitModuleBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitInterfaceBlock(node As InterfaceBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitInterfaceBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitEnumBlock(node As EnumBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitEnumBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitPropertyBlock(node As PropertyBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitPropertyBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitEventBlock(node As EventBlockSyntax) As VisualBasicSyntaxNode
If _declarationBlocksBeingVisited IsNot Nothing Then
_declarationBlocksBeingVisited.Push(node)
End If
Dim result = MyBase.VisitEventBlock(node)
If _declarationBlocksBeingVisited IsNot Nothing Then
Dim n = _declarationBlocksBeingVisited.Pop()
Debug.Assert(n Is node)
End If
Return result
End Function
Public Overrides Function VisitIfDirectiveTrivia(node As IfDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitIfDirectiveTrivia(node)
If Me._notClosedIfDirectives IsNot Nothing AndAlso Me._notClosedIfDirectives.Contains(node) Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_LbExpectedEndIf)
End If
Return rewritten
End Function
Public Overrides Function VisitRegionDirectiveTrivia(node As RegionDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitRegionDirectiveTrivia(node)
If Me._notClosedRegionDirectives IsNot Nothing AndAlso Me._notClosedRegionDirectives.Contains(node) Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_ExpectedEndRegion)
ElseIf Not _regionsAreAllowedEverywhere
rewritten = VerifyRegionPlacement(node, rewritten)
End If
Return rewritten
End Function
Private Function VerifyRegionPlacement(original As VisualBasicSyntaxNode, rewritten As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
Dim containingBlock = _declarationBlocksBeingVisited.Peek()
' Ensure that the directive is inside the block, rather than is attached to it as a leading/trailing trivia
Debug.Assert(_declarationBlocksBeingVisited.Count > 1 OrElse containingBlock.Kind = SyntaxKind.CompilationUnit)
If _declarationBlocksBeingVisited.Count > 1 Then
If _tokenWithDirectivesBeingVisited Is containingBlock.GetFirstToken() Then
Dim leadingTrivia = _tokenWithDirectivesBeingVisited.GetLeadingTrivia()
If leadingTrivia IsNot Nothing AndAlso New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia).Nodes.Contains(original) Then
containingBlock = _declarationBlocksBeingVisited(_declarationBlocksBeingVisited.Count - 2)
End If
ElseIf _tokenWithDirectivesBeingVisited Is containingBlock.GetLastToken() Then
Dim trailingTrivia = _tokenWithDirectivesBeingVisited.GetTrailingTrivia()
If trailingTrivia IsNot Nothing AndAlso New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia).Nodes.Contains(original) Then
containingBlock = _declarationBlocksBeingVisited(_declarationBlocksBeingVisited.Count - 2)
End If
End If
End If
Dim reportAnError = Not IsValidContainingBlockForRegionInVB12(containingBlock)
If original.Kind = SyntaxKind.RegionDirectiveTrivia Then
_parentsOfRegionDirectivesAwaitingClosure.Push(containingBlock)
Else
Debug.Assert(original.Kind = SyntaxKind.EndRegionDirectiveTrivia)
If _parentsOfRegionDirectivesAwaitingClosure.Count > 0 Then
Dim regionBeginContainingBlock = _parentsOfRegionDirectivesAwaitingClosure.Pop()
If regionBeginContainingBlock IsNot containingBlock AndAlso IsValidContainingBlockForRegionInVB12(regionBeginContainingBlock) Then
reportAnError = True
End If
End If
End If
If reportAnError Then
rewritten = _parser.ReportFeatureUnavailable(Feature.RegionsEverywhere, rewritten)
End If
Return rewritten
End Function
Private Shared Function IsValidContainingBlockForRegionInVB12(containingBlock As VisualBasicSyntaxNode) As Boolean
Select Case containingBlock.Kind
Case SyntaxKind.FunctionBlock,
SyntaxKind.SubBlock,
SyntaxKind.ConstructorBlock,
SyntaxKind.OperatorBlock,
SyntaxKind.SetAccessorBlock,
SyntaxKind.GetAccessorBlock,
SyntaxKind.AddHandlerAccessorBlock,
SyntaxKind.RemoveHandlerAccessorBlock,
SyntaxKind.RaiseEventAccessorBlock
Return False
End Select
Return True
End Function
Public Overrides Function VisitEndRegionDirectiveTrivia(node As EndRegionDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitEndRegionDirectiveTrivia(node)
If Not _regionsAreAllowedEverywhere Then
rewritten = VerifyRegionPlacement(node, rewritten)
End If
Return rewritten
End Function
Public Overrides Function VisitExternalSourceDirectiveTrivia(node As ExternalSourceDirectiveTriviaSyntax) As VisualBasicSyntaxNode
#If DEBUG Then
Debug.Assert(_processedNodesWithoutDuplication.Add(node))
#End If
Dim rewritten = MyBase.VisitExternalSourceDirectiveTrivia(node)
If Me._notClosedExternalSourceDirective Is node Then
rewritten = Parser.ReportSyntaxError(rewritten, ERRID.ERR_ExpectedEndExternalSource)
End If
Return rewritten
End Function
Public Overrides Function Visit(node As VisualBasicSyntaxNode) As VisualBasicSyntaxNode
If node Is Nothing OrElse Not node.ContainsDirectives Then
Return node
End If
Return node.Accept(Me)
End Function
Public Overrides Function VisitSyntaxToken(token As SyntaxToken) As SyntaxToken
If token Is Nothing OrElse Not token.ContainsDirectives Then
Return token
End If
Debug.Assert(_tokenWithDirectivesBeingVisited Is Nothing)
_tokenWithDirectivesBeingVisited = token
Dim leadingTrivia = token.GetLeadingTrivia()
Dim trailingTrivia = token.GetTrailingTrivia()
If leadingTrivia IsNot Nothing Then
Dim rewritten = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(leadingTrivia)).Node
If leadingTrivia IsNot rewritten Then
token = DirectCast(token.WithLeadingTrivia(rewritten), SyntaxToken)
End If
End If
If trailingTrivia IsNot Nothing Then
Dim rewritten = VisitList(New CodeAnalysis.Syntax.InternalSyntax.SyntaxList(Of VisualBasicSyntaxNode)(trailingTrivia)).Node
If trailingTrivia IsNot rewritten Then
token = DirectCast(token.WithTrailingTrivia(rewritten), SyntaxToken)
End If
End If
_tokenWithDirectivesBeingVisited = Nothing
Return token
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/Core/Portable/InternalUtilities/CommandLineUtilities.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
namespace Roslyn.Utilities
{
internal static class CommandLineUtilities
{
/// <summary>
/// Split a command line by the same rules as Main would get the commands except the original
/// state of backslashes and quotes are preserved. For example in normal Windows command line
/// parsing the following command lines would produce equivalent Main arguments:
///
/// - /r:a,b
/// - /r:"a,b"
///
/// This method will differ as the latter will have the quotes preserved. The only case where
/// quotes are removed is when the entire argument is surrounded by quotes without any inner
/// quotes.
/// </summary>
/// <remarks>
/// Rules for command line parsing, according to MSDN:
///
/// Arguments are delimited by white space, which is either a space or a tab.
///
/// A string surrounded by double quotation marks ("string") is interpreted
/// as a single argument, regardless of white space contained within.
/// A quoted string can be embedded in an argument.
///
/// A double quotation mark preceded by a backslash (\") is interpreted as a
/// literal double quotation mark character (").
///
/// Backslashes are interpreted literally, unless they immediately precede a
/// double quotation mark.
///
/// If an even number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is interpreted as a string delimiter.
///
/// If an odd number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is "escaped" by the remaining backslash,
/// causing a literal double quotation mark (") to be placed in argv.
/// </remarks>
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)
{
return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _);
}
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)
{
var list = new List<string>();
SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar);
return list;
}
public static void SplitCommandLineIntoArguments(ReadOnlySpan<char> commandLine, bool removeHashComments, StringBuilder builder, List<string> list, out char? illegalChar)
{
var i = 0;
builder.Length = 0;
illegalChar = null;
while (i < commandLine.Length)
{
while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))
{
i++;
}
if (i == commandLine.Length)
{
break;
}
if (commandLine[i] == '#' && removeHashComments)
{
break;
}
var quoteCount = 0;
builder.Length = 0;
while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))
{
var current = commandLine[i];
switch (current)
{
case '\\':
{
var slashCount = 0;
do
{
builder.Append(commandLine[i]);
i++;
slashCount++;
} while (i < commandLine.Length && commandLine[i] == '\\');
// Slashes not followed by a quote character can be ignored for now
if (i >= commandLine.Length || commandLine[i] != '"')
{
break;
}
// If there is an odd number of slashes then it is escaping the quote
// otherwise it is just a quote.
if (slashCount % 2 == 0)
{
quoteCount++;
}
builder.Append('"');
i++;
break;
}
case '"':
builder.Append(current);
quoteCount++;
i++;
break;
default:
if ((current >= 0x1 && current <= 0x1f) || current == '|')
{
if (illegalChar == null)
{
illegalChar = current;
}
}
else
{
builder.Append(current);
}
i++;
break;
}
}
// If the quote string is surrounded by quotes with no interior quotes then
// remove the quotes here.
if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"')
{
builder.Remove(0, length: 1);
builder.Remove(builder.Length - 1, length: 1);
}
if (builder.Length > 0)
{
list.Add(builder.ToString());
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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.Text;
namespace Roslyn.Utilities
{
internal static class CommandLineUtilities
{
/// <summary>
/// Split a command line by the same rules as Main would get the commands except the original
/// state of backslashes and quotes are preserved. For example in normal Windows command line
/// parsing the following command lines would produce equivalent Main arguments:
///
/// - /r:a,b
/// - /r:"a,b"
///
/// This method will differ as the latter will have the quotes preserved. The only case where
/// quotes are removed is when the entire argument is surrounded by quotes without any inner
/// quotes.
/// </summary>
/// <remarks>
/// Rules for command line parsing, according to MSDN:
///
/// Arguments are delimited by white space, which is either a space or a tab.
///
/// A string surrounded by double quotation marks ("string") is interpreted
/// as a single argument, regardless of white space contained within.
/// A quoted string can be embedded in an argument.
///
/// A double quotation mark preceded by a backslash (\") is interpreted as a
/// literal double quotation mark character (").
///
/// Backslashes are interpreted literally, unless they immediately precede a
/// double quotation mark.
///
/// If an even number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is interpreted as a string delimiter.
///
/// If an odd number of backslashes is followed by a double quotation mark,
/// one backslash is placed in the argv array for every pair of backslashes,
/// and the double quotation mark is "escaped" by the remaining backslash,
/// causing a literal double quotation mark (") to be placed in argv.
/// </remarks>
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments)
{
return SplitCommandLineIntoArguments(commandLine, removeHashComments, out _);
}
public static List<string> SplitCommandLineIntoArguments(string commandLine, bool removeHashComments, out char? illegalChar)
{
var list = new List<string>();
SplitCommandLineIntoArguments(commandLine.AsSpan(), removeHashComments, new StringBuilder(), list, out illegalChar);
return list;
}
public static void SplitCommandLineIntoArguments(ReadOnlySpan<char> commandLine, bool removeHashComments, StringBuilder builder, List<string> list, out char? illegalChar)
{
var i = 0;
builder.Length = 0;
illegalChar = null;
while (i < commandLine.Length)
{
while (i < commandLine.Length && char.IsWhiteSpace(commandLine[i]))
{
i++;
}
if (i == commandLine.Length)
{
break;
}
if (commandLine[i] == '#' && removeHashComments)
{
break;
}
var quoteCount = 0;
builder.Length = 0;
while (i < commandLine.Length && (!char.IsWhiteSpace(commandLine[i]) || (quoteCount % 2 != 0)))
{
var current = commandLine[i];
switch (current)
{
case '\\':
{
var slashCount = 0;
do
{
builder.Append(commandLine[i]);
i++;
slashCount++;
} while (i < commandLine.Length && commandLine[i] == '\\');
// Slashes not followed by a quote character can be ignored for now
if (i >= commandLine.Length || commandLine[i] != '"')
{
break;
}
// If there is an odd number of slashes then it is escaping the quote
// otherwise it is just a quote.
if (slashCount % 2 == 0)
{
quoteCount++;
}
builder.Append('"');
i++;
break;
}
case '"':
builder.Append(current);
quoteCount++;
i++;
break;
default:
if ((current >= 0x1 && current <= 0x1f) || current == '|')
{
if (illegalChar == null)
{
illegalChar = current;
}
}
else
{
builder.Append(current);
}
i++;
break;
}
}
// If the quote string is surrounded by quotes with no interior quotes then
// remove the quotes here.
if (quoteCount == 2 && builder[0] == '"' && builder[builder.Length - 1] == '"')
{
builder.Remove(0, length: 1);
builder.Remove(builder.Length - 1, length: 1);
}
if (builder.Length > 0)
{
list.Add(builder.ToString());
}
}
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Analyzers/CSharp/CodeFixes/PopulateSwitch/CSharpPopulateSwitchExpressionCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.PopulateSwitch;
namespace Microsoft.CodeAnalysis.CSharp.PopulateSwitch
{
using static SyntaxFactory;
[ExportCodeFixProvider(LanguageNames.CSharp,
Name = PredefinedCodeFixProviderNames.PopulateSwitchExpression), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.ImplementInterface)]
internal class CSharpPopulateSwitchExpressionCodeFixProvider
: AbstractPopulateSwitchExpressionCodeFixProvider<
ExpressionSyntax,
SwitchExpressionSyntax,
SwitchExpressionArmSyntax,
MemberAccessExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpPopulateSwitchExpressionCodeFixProvider()
{
}
protected override SwitchExpressionArmSyntax CreateDefaultSwitchArm(SyntaxGenerator generator, Compilation compilation)
=> SwitchExpressionArm(DiscardPattern(), Exception(generator, compilation));
protected override SwitchExpressionArmSyntax CreateSwitchArm(SyntaxGenerator generator, Compilation compilation, MemberAccessExpressionSyntax caseLabel)
=> SwitchExpressionArm(ConstantPattern(caseLabel), Exception(generator, compilation));
protected override SwitchExpressionSyntax InsertSwitchArms(SyntaxGenerator generator, SwitchExpressionSyntax switchNode, int insertLocation, List<SwitchExpressionArmSyntax> newArms)
{
// If the existing switch expression ends with a comma, then ensure that we preserve
// that. Also do this for an empty switch statement.
if (switchNode.Arms.Count == 0 ||
!switchNode.Arms.GetWithSeparators().LastOrDefault().IsNode)
{
return switchNode.WithArms(switchNode.Arms.InsertRangeWithTrailingSeparator(
insertLocation, newArms, SyntaxKind.CommaToken));
}
return switchNode.WithArms(switchNode.Arms.InsertRange(insertLocation, newArms));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.PopulateSwitch;
namespace Microsoft.CodeAnalysis.CSharp.PopulateSwitch
{
using static SyntaxFactory;
[ExportCodeFixProvider(LanguageNames.CSharp,
Name = PredefinedCodeFixProviderNames.PopulateSwitchExpression), Shared]
[ExtensionOrder(After = PredefinedCodeFixProviderNames.ImplementInterface)]
internal class CSharpPopulateSwitchExpressionCodeFixProvider
: AbstractPopulateSwitchExpressionCodeFixProvider<
ExpressionSyntax,
SwitchExpressionSyntax,
SwitchExpressionArmSyntax,
MemberAccessExpressionSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpPopulateSwitchExpressionCodeFixProvider()
{
}
protected override SwitchExpressionArmSyntax CreateDefaultSwitchArm(SyntaxGenerator generator, Compilation compilation)
=> SwitchExpressionArm(DiscardPattern(), Exception(generator, compilation));
protected override SwitchExpressionArmSyntax CreateSwitchArm(SyntaxGenerator generator, Compilation compilation, MemberAccessExpressionSyntax caseLabel)
=> SwitchExpressionArm(ConstantPattern(caseLabel), Exception(generator, compilation));
protected override SwitchExpressionSyntax InsertSwitchArms(SyntaxGenerator generator, SwitchExpressionSyntax switchNode, int insertLocation, List<SwitchExpressionArmSyntax> newArms)
{
// If the existing switch expression ends with a comma, then ensure that we preserve
// that. Also do this for an empty switch statement.
if (switchNode.Arms.Count == 0 ||
!switchNode.Arms.GetWithSeparators().LastOrDefault().IsNode)
{
return switchNode.WithArms(switchNode.Arms.InsertRangeWithTrailingSeparator(
insertLocation, newArms, SyntaxKind.CommaToken));
}
return switchNode.WithArms(switchNode.Arms.InsertRange(insertLocation, newArms));
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Features/VisualBasic/Portable/ExtractMethod/VisualBasicMethodExtractor.VisualBasicCodeGenerator.CallSiteContainerRewriter.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Partial Friend Class VisualBasicMethodExtractor
Partial Private MustInherit Class VisualBasicCodeGenerator
Private Class CallSiteContainerRewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _outmostCallSiteContainer As SyntaxNode
Private ReadOnly _statementsOrFieldToInsert As IEnumerable(Of StatementSyntax)
Private ReadOnly _variableToRemoveMap As HashSet(Of SyntaxAnnotation)
Private ReadOnly _firstStatementOrFieldToReplace As StatementSyntax
Private ReadOnly _lastStatementOrFieldToReplace As StatementSyntax
Private Shared ReadOnly s_removeAnnotation As SyntaxAnnotation = New SyntaxAnnotation()
Public Sub New(outmostCallSiteContainer As SyntaxNode,
variableToRemoveMap As HashSet(Of SyntaxAnnotation),
firstStatementOrFieldToReplace As StatementSyntax,
lastStatementOrFieldToReplace As StatementSyntax,
statementsOrFieldToInsert As IEnumerable(Of StatementSyntax))
Contract.ThrowIfNull(outmostCallSiteContainer)
Contract.ThrowIfNull(variableToRemoveMap)
Contract.ThrowIfNull(firstStatementOrFieldToReplace)
Contract.ThrowIfNull(lastStatementOrFieldToReplace)
Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty())
Me._outmostCallSiteContainer = outmostCallSiteContainer
Me._variableToRemoveMap = variableToRemoveMap
Me._statementsOrFieldToInsert = statementsOrFieldToInsert
Me._firstStatementOrFieldToReplace = firstStatementOrFieldToReplace
Me._lastStatementOrFieldToReplace = lastStatementOrFieldToReplace
Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace.Parent Is Me._lastStatementOrFieldToReplace.Parent)
End Sub
Public Function Generate() As SyntaxNode
Dim result = Visit(Me._outmostCallSiteContainer)
' remove any nodes annotated for removal
If result.ContainsAnnotations Then
Dim nodesToRemove = result.DescendantNodes(Function(n) n.ContainsAnnotations).Where(Function(n) n.HasAnnotation(s_removeAnnotation))
result = result.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia)
End If
Return result
End Function
Private ReadOnly Property ContainerOfStatementsOrFieldToReplace() As SyntaxNode
Get
Return Me._firstStatementOrFieldToReplace.Parent
End Get
End Property
Public Overrides Function VisitLocalDeclarationStatement(node As LocalDeclarationStatementSyntax) As SyntaxNode
node = CType(MyBase.VisitLocalDeclarationStatement(node), LocalDeclarationStatementSyntax)
Dim expressionStatements = New List(Of StatementSyntax)()
Dim variableDeclarators = New List(Of VariableDeclaratorSyntax)()
Dim triviaList = New List(Of SyntaxTrivia)()
If Not Me._variableToRemoveMap.ProcessLocalDeclarationStatement(node, expressionStatements, variableDeclarators, triviaList) Then
Contract.ThrowIfFalse(expressionStatements.Count = 0)
Return node
End If
Contract.ThrowIfFalse(expressionStatements.Count = 0)
If variableDeclarators.Count = 0 AndAlso
triviaList.Any(Function(t) t.Kind <> SyntaxKind.WhitespaceTrivia AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia) Then
' well, there are trivia associated with the node.
' we can't just delete the node since then, we will lose
' the trivia. unfortunately, it is not easy to attach the trivia
' to next token. for now, create an empty statement and associate the
' trivia to the statement
' TODO : think about a way to trivia attached to next token
Return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken).WithLeadingTrivia(SyntaxFactory.TriviaList(triviaList)))
End If
' return survived var decls
If variableDeclarators.Count > 0 Then
Return SyntaxFactory.LocalDeclarationStatement(
node.Modifiers,
SyntaxFactory.SeparatedList(variableDeclarators)).WithPrependedLeadingTrivia(triviaList)
End If
Return node.WithAdditionalAnnotations(s_removeAnnotation)
End Function
Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitMethodBlock(node)
End If
Return node.WithSubOrFunctionStatement(ReplaceStatementIfNeeded(node.SubOrFunctionStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitConstructorBlock(node)
End If
Return node.WithSubNewStatement(ReplaceStatementIfNeeded(node.SubNewStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitOperatorBlock(node)
End If
Return node.WithOperatorStatement(ReplaceStatementIfNeeded(node.OperatorStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitAccessorBlock(node)
End If
Return node.WithAccessorStatement(ReplaceStatementIfNeeded(node.AccessorStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the switch section
Return MyBase.VisitWhileBlock(node)
End If
Return node.WithWhileStatement(ReplaceStatementIfNeeded(node.WhileStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitUsingBlock(node As UsingBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitUsingBlock(node)
End If
Return node.WithUsingStatement(ReplaceStatementIfNeeded(node.UsingStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitSyncLockBlock(node As SyncLockBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSyncLockBlock(node)
End If
Return node.WithSyncLockStatement(ReplaceStatementIfNeeded(node.SyncLockStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitWithBlock(node As WithBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitWithBlock(node)
End If
Return node.WithWithStatement(ReplaceStatementIfNeeded(node.WithStatement)).
WithStatements(ReplaceStatementsIfNeeded(node.Statements))
End Function
Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSingleLineIfStatement(node)
End If
Return SyntaxFactory.SingleLineIfStatement(node.IfKeyword,
node.Condition,
node.ThenKeyword,
VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True)),
node.ElseClause)
End Function
Public Overrides Function VisitSingleLineElseClause(node As SingleLineElseClauseSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSingleLineElseClause(node)
End If
Return SyntaxFactory.SingleLineElseClause(node.ElseKeyword, VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True)))
End Function
Public Overrides Function VisitMultiLineIfBlock(node As MultiLineIfBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitMultiLineIfBlock(node)
End If
Return node.WithIfStatement(ReplaceStatementIfNeeded(node.IfStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitElseBlock(node As ElseBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitElseBlock(node)
End If
Return node.WithElseStatement(ReplaceStatementIfNeeded(node.ElseStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitTryBlock(node As TryBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitTryBlock(node)
End If
Return node.WithTryStatement(ReplaceStatementIfNeeded(node.TryStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitCatchBlock(node As CatchBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitCatchBlock(node)
End If
Return node.WithCatchStatement(ReplaceStatementIfNeeded(node.CatchStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitFinallyBlock(node As FinallyBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitFinallyBlock(node)
End If
Return node.WithFinallyStatement(ReplaceStatementIfNeeded(node.FinallyStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitSelectBlock(node As SelectBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSelectBlock(node)
End If
Return node.WithSelectStatement(ReplaceStatementIfNeeded(node.SelectStatement)).
WithCaseBlocks(VisitList(node.CaseBlocks)).
WithEndSelectStatement(ReplaceStatementIfNeeded(node.EndSelectStatement))
End Function
Public Overrides Function VisitCaseBlock(node As CaseBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitCaseBlock(node)
End If
Return node.WithCaseStatement(ReplaceStatementIfNeeded(node.CaseStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitDoLoopBlock(node)
End If
Return node.WithDoStatement(ReplaceStatementIfNeeded(node.DoStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithLoopStatement(ReplaceStatementIfNeeded(node.LoopStatement))
End Function
Public Overrides Function VisitForBlock(node As ForBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitForBlock(node)
End If
Return node.WithForStatement(ReplaceStatementIfNeeded(node.ForStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement))
End Function
Public Overrides Function VisitForEachBlock(node As ForEachBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitForEachBlock(node)
End If
Return node.WithForEachStatement(ReplaceStatementIfNeeded(node.ForEachStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement))
End Function
Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSingleLineLambdaExpression(node)
End If
Dim body = SyntaxFactory.SingletonList(DirectCast(node.Body, StatementSyntax))
Return node.WithBody(VisitList(ReplaceStatementsIfNeeded(body, colon:=True)).First()).
WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader))
End Function
Public Overrides Function VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitMultiLineLambdaExpression(node)
End If
Return node.WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader))
End Function
Private Function ReplaceStatementIfNeeded(Of T As StatementSyntax)(statement As T) As T
Contract.ThrowIfNull(statement)
' if all three same
If (statement IsNot _firstStatementOrFieldToReplace) OrElse (Me._firstStatementOrFieldToReplace IsNot Me._lastStatementOrFieldToReplace) Then
Return statement
End If
Contract.ThrowIfFalse(Me._statementsOrFieldToInsert.Count() = 1)
Return CType(Me._statementsOrFieldToInsert.Single(), T)
End Function
Private Function ReplaceStatementsIfNeeded(statements As SyntaxList(Of StatementSyntax), Optional colon As Boolean = False) As SyntaxList(Of StatementSyntax)
Dim newStatements = New List(Of StatementSyntax)(statements)
Dim firstStatementIndex = newStatements.FindIndex(Function(s) s Is Me._firstStatementOrFieldToReplace)
' looks like statements belong to parent's Begin statement. there is nothing we need to do here.
If firstStatementIndex < 0 Then
Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace Is Me._lastStatementOrFieldToReplace)
Return statements
End If
Dim lastStatementIndex = newStatements.FindIndex(Function(s) s Is Me._lastStatementOrFieldToReplace)
Contract.ThrowIfFalse(lastStatementIndex >= 0)
Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex)
' okay, this visit contains the statement
' remove statement that must be removed
statements = statements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1)
' insert new statements
Return statements.InsertRange(firstStatementIndex, Join(Me._statementsOrFieldToInsert, colon).ToArray())
End Function
Private Shared Function Join(statements As IEnumerable(Of StatementSyntax), colon As Boolean) As IEnumerable(Of StatementSyntax)
If Not colon Then
Return statements
End If
Dim removeEndOfLine = Function(t As SyntaxTrivia) Not t.IsElastic() AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia
Dim i = 0
Dim count = statements.Count()
Dim trivia = SyntaxFactory.ColonTrivia(SyntaxFacts.GetText(SyntaxKind.ColonTrivia))
Dim newStatements = New List(Of StatementSyntax)
For Each statement In statements
statement = statement.WithLeadingTrivia(statement.GetLeadingTrivia().Where(removeEndOfLine))
If i < count - 1 Then
statement = statement.WithTrailingTrivia(statement.GetTrailingTrivia().Where(removeEndOfLine).Concat(trivia))
End If
newStatements.Add(statement)
i += 1
Next
Return newStatements
End Function
Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitModuleBlock(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitClassBlock(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitStructureBlock(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitCompilationUnit(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
End Class
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.ExtractMethod
Partial Friend Class VisualBasicMethodExtractor
Partial Private MustInherit Class VisualBasicCodeGenerator
Private Class CallSiteContainerRewriter
Inherits VisualBasicSyntaxRewriter
Private ReadOnly _outmostCallSiteContainer As SyntaxNode
Private ReadOnly _statementsOrFieldToInsert As IEnumerable(Of StatementSyntax)
Private ReadOnly _variableToRemoveMap As HashSet(Of SyntaxAnnotation)
Private ReadOnly _firstStatementOrFieldToReplace As StatementSyntax
Private ReadOnly _lastStatementOrFieldToReplace As StatementSyntax
Private Shared ReadOnly s_removeAnnotation As SyntaxAnnotation = New SyntaxAnnotation()
Public Sub New(outmostCallSiteContainer As SyntaxNode,
variableToRemoveMap As HashSet(Of SyntaxAnnotation),
firstStatementOrFieldToReplace As StatementSyntax,
lastStatementOrFieldToReplace As StatementSyntax,
statementsOrFieldToInsert As IEnumerable(Of StatementSyntax))
Contract.ThrowIfNull(outmostCallSiteContainer)
Contract.ThrowIfNull(variableToRemoveMap)
Contract.ThrowIfNull(firstStatementOrFieldToReplace)
Contract.ThrowIfNull(lastStatementOrFieldToReplace)
Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty())
Me._outmostCallSiteContainer = outmostCallSiteContainer
Me._variableToRemoveMap = variableToRemoveMap
Me._statementsOrFieldToInsert = statementsOrFieldToInsert
Me._firstStatementOrFieldToReplace = firstStatementOrFieldToReplace
Me._lastStatementOrFieldToReplace = lastStatementOrFieldToReplace
Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace.Parent Is Me._lastStatementOrFieldToReplace.Parent)
End Sub
Public Function Generate() As SyntaxNode
Dim result = Visit(Me._outmostCallSiteContainer)
' remove any nodes annotated for removal
If result.ContainsAnnotations Then
Dim nodesToRemove = result.DescendantNodes(Function(n) n.ContainsAnnotations).Where(Function(n) n.HasAnnotation(s_removeAnnotation))
result = result.RemoveNodes(nodesToRemove, SyntaxRemoveOptions.KeepNoTrivia)
End If
Return result
End Function
Private ReadOnly Property ContainerOfStatementsOrFieldToReplace() As SyntaxNode
Get
Return Me._firstStatementOrFieldToReplace.Parent
End Get
End Property
Public Overrides Function VisitLocalDeclarationStatement(node As LocalDeclarationStatementSyntax) As SyntaxNode
node = CType(MyBase.VisitLocalDeclarationStatement(node), LocalDeclarationStatementSyntax)
Dim expressionStatements = New List(Of StatementSyntax)()
Dim variableDeclarators = New List(Of VariableDeclaratorSyntax)()
Dim triviaList = New List(Of SyntaxTrivia)()
If Not Me._variableToRemoveMap.ProcessLocalDeclarationStatement(node, expressionStatements, variableDeclarators, triviaList) Then
Contract.ThrowIfFalse(expressionStatements.Count = 0)
Return node
End If
Contract.ThrowIfFalse(expressionStatements.Count = 0)
If variableDeclarators.Count = 0 AndAlso
triviaList.Any(Function(t) t.Kind <> SyntaxKind.WhitespaceTrivia AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia) Then
' well, there are trivia associated with the node.
' we can't just delete the node since then, we will lose
' the trivia. unfortunately, it is not easy to attach the trivia
' to next token. for now, create an empty statement and associate the
' trivia to the statement
' TODO : think about a way to trivia attached to next token
Return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken).WithLeadingTrivia(SyntaxFactory.TriviaList(triviaList)))
End If
' return survived var decls
If variableDeclarators.Count > 0 Then
Return SyntaxFactory.LocalDeclarationStatement(
node.Modifiers,
SyntaxFactory.SeparatedList(variableDeclarators)).WithPrependedLeadingTrivia(triviaList)
End If
Return node.WithAdditionalAnnotations(s_removeAnnotation)
End Function
Public Overrides Function VisitMethodBlock(node As MethodBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitMethodBlock(node)
End If
Return node.WithSubOrFunctionStatement(ReplaceStatementIfNeeded(node.SubOrFunctionStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitConstructorBlock(node As ConstructorBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitConstructorBlock(node)
End If
Return node.WithSubNewStatement(ReplaceStatementIfNeeded(node.SubNewStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitOperatorBlock(node As OperatorBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitOperatorBlock(node)
End If
Return node.WithOperatorStatement(ReplaceStatementIfNeeded(node.OperatorStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitAccessorBlock(node As AccessorBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitAccessorBlock(node)
End If
Return node.WithAccessorStatement(ReplaceStatementIfNeeded(node.AccessorStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitWhileBlock(node As WhileBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the switch section
Return MyBase.VisitWhileBlock(node)
End If
Return node.WithWhileStatement(ReplaceStatementIfNeeded(node.WhileStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitUsingBlock(node As UsingBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitUsingBlock(node)
End If
Return node.WithUsingStatement(ReplaceStatementIfNeeded(node.UsingStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitSyncLockBlock(node As SyncLockBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSyncLockBlock(node)
End If
Return node.WithSyncLockStatement(ReplaceStatementIfNeeded(node.SyncLockStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitWithBlock(node As WithBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitWithBlock(node)
End If
Return node.WithWithStatement(ReplaceStatementIfNeeded(node.WithStatement)).
WithStatements(ReplaceStatementsIfNeeded(node.Statements))
End Function
Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSingleLineIfStatement(node)
End If
Return SyntaxFactory.SingleLineIfStatement(node.IfKeyword,
node.Condition,
node.ThenKeyword,
VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True)),
node.ElseClause)
End Function
Public Overrides Function VisitSingleLineElseClause(node As SingleLineElseClauseSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSingleLineElseClause(node)
End If
Return SyntaxFactory.SingleLineElseClause(node.ElseKeyword, VisitList(ReplaceStatementsIfNeeded(node.Statements, colon:=True)))
End Function
Public Overrides Function VisitMultiLineIfBlock(node As MultiLineIfBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitMultiLineIfBlock(node)
End If
Return node.WithIfStatement(ReplaceStatementIfNeeded(node.IfStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitElseBlock(node As ElseBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitElseBlock(node)
End If
Return node.WithElseStatement(ReplaceStatementIfNeeded(node.ElseStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitTryBlock(node As TryBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitTryBlock(node)
End If
Return node.WithTryStatement(ReplaceStatementIfNeeded(node.TryStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitCatchBlock(node As CatchBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitCatchBlock(node)
End If
Return node.WithCatchStatement(ReplaceStatementIfNeeded(node.CatchStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitFinallyBlock(node As FinallyBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitFinallyBlock(node)
End If
Return node.WithFinallyStatement(ReplaceStatementIfNeeded(node.FinallyStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitSelectBlock(node As SelectBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSelectBlock(node)
End If
Return node.WithSelectStatement(ReplaceStatementIfNeeded(node.SelectStatement)).
WithCaseBlocks(VisitList(node.CaseBlocks)).
WithEndSelectStatement(ReplaceStatementIfNeeded(node.EndSelectStatement))
End Function
Public Overrides Function VisitCaseBlock(node As CaseBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitCaseBlock(node)
End If
Return node.WithCaseStatement(ReplaceStatementIfNeeded(node.CaseStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements)))
End Function
Public Overrides Function VisitDoLoopBlock(node As DoLoopBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitDoLoopBlock(node)
End If
Return node.WithDoStatement(ReplaceStatementIfNeeded(node.DoStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithLoopStatement(ReplaceStatementIfNeeded(node.LoopStatement))
End Function
Public Overrides Function VisitForBlock(node As ForBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitForBlock(node)
End If
Return node.WithForStatement(ReplaceStatementIfNeeded(node.ForStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement))
End Function
Public Overrides Function VisitForEachBlock(node As ForEachBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitForEachBlock(node)
End If
Return node.WithForEachStatement(ReplaceStatementIfNeeded(node.ForEachStatement)).
WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithNextStatement(ReplaceStatementIfNeeded(node.NextStatement))
End Function
Public Overrides Function VisitSingleLineLambdaExpression(node As SingleLineLambdaExpressionSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitSingleLineLambdaExpression(node)
End If
Dim body = SyntaxFactory.SingletonList(DirectCast(node.Body, StatementSyntax))
Return node.WithBody(VisitList(ReplaceStatementsIfNeeded(body, colon:=True)).First()).
WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader))
End Function
Public Overrides Function VisitMultiLineLambdaExpression(node As MultiLineLambdaExpressionSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
Return MyBase.VisitMultiLineLambdaExpression(node)
End If
Return node.WithStatements(VisitList(ReplaceStatementsIfNeeded(node.Statements))).
WithSubOrFunctionHeader(ReplaceStatementIfNeeded(node.SubOrFunctionHeader))
End Function
Private Function ReplaceStatementIfNeeded(Of T As StatementSyntax)(statement As T) As T
Contract.ThrowIfNull(statement)
' if all three same
If (statement IsNot _firstStatementOrFieldToReplace) OrElse (Me._firstStatementOrFieldToReplace IsNot Me._lastStatementOrFieldToReplace) Then
Return statement
End If
Contract.ThrowIfFalse(Me._statementsOrFieldToInsert.Count() = 1)
Return CType(Me._statementsOrFieldToInsert.Single(), T)
End Function
Private Function ReplaceStatementsIfNeeded(statements As SyntaxList(Of StatementSyntax), Optional colon As Boolean = False) As SyntaxList(Of StatementSyntax)
Dim newStatements = New List(Of StatementSyntax)(statements)
Dim firstStatementIndex = newStatements.FindIndex(Function(s) s Is Me._firstStatementOrFieldToReplace)
' looks like statements belong to parent's Begin statement. there is nothing we need to do here.
If firstStatementIndex < 0 Then
Contract.ThrowIfFalse(Me._firstStatementOrFieldToReplace Is Me._lastStatementOrFieldToReplace)
Return statements
End If
Dim lastStatementIndex = newStatements.FindIndex(Function(s) s Is Me._lastStatementOrFieldToReplace)
Contract.ThrowIfFalse(lastStatementIndex >= 0)
Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex)
' okay, this visit contains the statement
' remove statement that must be removed
statements = statements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1)
' insert new statements
Return statements.InsertRange(firstStatementIndex, Join(Me._statementsOrFieldToInsert, colon).ToArray())
End Function
Private Shared Function Join(statements As IEnumerable(Of StatementSyntax), colon As Boolean) As IEnumerable(Of StatementSyntax)
If Not colon Then
Return statements
End If
Dim removeEndOfLine = Function(t As SyntaxTrivia) Not t.IsElastic() AndAlso t.Kind <> SyntaxKind.EndOfLineTrivia
Dim i = 0
Dim count = statements.Count()
Dim trivia = SyntaxFactory.ColonTrivia(SyntaxFacts.GetText(SyntaxKind.ColonTrivia))
Dim newStatements = New List(Of StatementSyntax)
For Each statement In statements
statement = statement.WithLeadingTrivia(statement.GetLeadingTrivia().Where(removeEndOfLine))
If i < count - 1 Then
statement = statement.WithTrailingTrivia(statement.GetTrailingTrivia().Where(removeEndOfLine).Concat(trivia))
End If
newStatements.Add(statement)
i += 1
Next
Return newStatements
End Function
Public Overrides Function VisitModuleBlock(ByVal node As ModuleBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitModuleBlock(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
Public Overrides Function VisitClassBlock(ByVal node As ClassBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitClassBlock(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
Public Overrides Function VisitStructureBlock(ByVal node As StructureBlockSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitStructureBlock(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
Public Overrides Function VisitCompilationUnit(node As CompilationUnitSyntax) As SyntaxNode
If node IsNot Me.ContainerOfStatementsOrFieldToReplace Then
' make sure we visit nodes under the block
Return MyBase.VisitCompilationUnit(node)
End If
Return node.WithMembers(VisitList(ReplaceStatementsIfNeeded(node.Members)))
End Function
End Class
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Workspaces/Core/Portable/ProjectTelemetry/IRemoteProjectTelemetryService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ProjectTelemetry
{
/// <summary>
/// Interface to allow host (VS) to inform the OOP service to start incrementally analyzing and
/// reporting results back to the host.
/// </summary>
internal interface IRemoteProjectTelemetryService
{
internal interface ICallback
{
ValueTask ReportProjectTelemetryDataAsync(RemoteServiceCallbackId callbackId, ProjectTelemetryData data, CancellationToken cancellationToken);
}
ValueTask ComputeProjectTelemetryAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellation);
}
[ExportRemoteServiceCallbackDispatcher(typeof(IRemoteProjectTelemetryService)), Shared]
internal sealed class RemoteProjectTelemetryServiceCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteProjectTelemetryService.ICallback
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteProjectTelemetryServiceCallbackDispatcher()
{
}
private IProjectTelemetryListener GetLogService(RemoteServiceCallbackId callbackId)
=> (IProjectTelemetryListener)GetCallback(callbackId);
public ValueTask ReportProjectTelemetryDataAsync(RemoteServiceCallbackId callbackId, ProjectTelemetryData data, CancellationToken cancellationToken)
=> GetLogService(callbackId).ReportProjectTelemetryDataAsync(data, cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Remote;
namespace Microsoft.CodeAnalysis.ProjectTelemetry
{
/// <summary>
/// Interface to allow host (VS) to inform the OOP service to start incrementally analyzing and
/// reporting results back to the host.
/// </summary>
internal interface IRemoteProjectTelemetryService
{
internal interface ICallback
{
ValueTask ReportProjectTelemetryDataAsync(RemoteServiceCallbackId callbackId, ProjectTelemetryData data, CancellationToken cancellationToken);
}
ValueTask ComputeProjectTelemetryAsync(RemoteServiceCallbackId callbackId, CancellationToken cancellation);
}
[ExportRemoteServiceCallbackDispatcher(typeof(IRemoteProjectTelemetryService)), Shared]
internal sealed class RemoteProjectTelemetryServiceCallbackDispatcher : RemoteServiceCallbackDispatcher, IRemoteProjectTelemetryService.ICallback
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RemoteProjectTelemetryServiceCallbackDispatcher()
{
}
private IProjectTelemetryListener GetLogService(RemoteServiceCallbackId callbackId)
=> (IProjectTelemetryListener)GetCallback(callbackId);
public ValueTask ReportProjectTelemetryDataAsync(RemoteServiceCallbackId callbackId, ProjectTelemetryData data, CancellationToken cancellationToken)
=> GetLogService(callbackId).ReportProjectTelemetryDataAsync(data, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/CSharp/Portable/SymbolDisplay/SymbolDisplayVisitor.Members.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
private const string IL_KEYWORD_MODOPT = "modopt";
private const string IL_KEYWORD_MODREQ = "modreq";
private void VisitFieldType(IFieldSymbol symbol)
{
symbol.Type.Accept(this.NotFirstVisitor);
}
public override void VisitField(IFieldSymbol symbol)
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
AddFieldModifiersIfRequired(symbol);
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType) &&
this.isFirstSymbolVisited &&
!IsEnumMember(symbol))
{
VisitFieldType(symbol);
AddSpace();
AddCustomModifiersIfRequired(symbol.CustomModifiers);
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) &&
IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
if (symbol.ContainingType.TypeKind == TypeKind.Enum)
{
builder.Add(CreatePart(SymbolDisplayPartKind.EnumMemberName, symbol, symbol.Name));
}
else if (symbol.IsConst)
{
builder.Add(CreatePart(SymbolDisplayPartKind.ConstantName, symbol, symbol.Name));
}
else
{
builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, symbol.Name));
}
if (this.isFirstSymbolVisited &&
format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeConstantValue) &&
symbol.IsConst &&
symbol.HasConstantValue &&
CanAddConstant(symbol.Type, symbol.ConstantValue))
{
AddSpace();
AddPunctuation(SyntaxKind.EqualsToken);
AddSpace();
AddConstantValue(symbol.Type, symbol.ConstantValue, preferNumericValueOrExpandedFlagsForEnum: IsEnumMember(symbol));
}
}
private static bool ShouldPropertyDisplayReadOnly(IPropertySymbol property)
{
if (property.ContainingType?.IsReadOnly == true)
{
return false;
}
// If at least one accessor is present and all present accessors are readonly, the property should be marked readonly.
var getMethod = property.GetMethod;
if (getMethod is object && !ShouldMethodDisplayReadOnly(getMethod, property))
{
return false;
}
var setMethod = property.SetMethod;
if (setMethod is object && !ShouldMethodDisplayReadOnly(setMethod, property))
{
return false;
}
return getMethod is object || setMethod is object;
}
private static bool ShouldMethodDisplayReadOnly(IMethodSymbol method, IPropertySymbol propertyOpt = null)
{
if (method.ContainingType?.IsReadOnly == true)
{
return false;
}
if ((method as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SourcePropertyAccessorSymbol sourceAccessor &&
(propertyOpt as Symbols.PublicModel.PropertySymbol)?.UnderlyingSymbol is SourcePropertySymbolBase sourceProperty)
{
// only display if the accessor is explicitly readonly
return sourceAccessor.LocalDeclaredReadOnly || sourceProperty.HasReadOnlyModifier;
}
else if (method is Symbols.PublicModel.MethodSymbol m)
{
return m.UnderlyingMethodSymbol.IsDeclaredReadOnly;
}
return false;
}
public override void VisitProperty(IPropertySymbol symbol)
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
if (ShouldPropertyDisplayReadOnly(symbol))
{
AddReadOnlyIfRequired();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType))
{
if (symbol.ReturnsByRef)
{
AddRefIfRequired();
}
else if (symbol.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
AddCustomModifiersIfRequired(symbol.RefCustomModifiers);
symbol.Type.Accept(this.NotFirstVisitor);
AddSpace();
AddCustomModifiersIfRequired(symbol.TypeCustomModifiers);
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) &&
IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
AddPropertyNameAndParameters(symbol);
if (format.PropertyStyle == SymbolDisplayPropertyStyle.ShowReadWriteDescriptor)
{
AddSpace();
AddPunctuation(SyntaxKind.OpenBraceToken);
AddAccessor(symbol, symbol.GetMethod, SyntaxKind.GetKeyword);
var keywordForSetAccessor = IsInitOnly(symbol.SetMethod) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword;
AddAccessor(symbol, symbol.SetMethod, keywordForSetAccessor);
AddSpace();
AddPunctuation(SyntaxKind.CloseBraceToken);
}
}
private static bool IsInitOnly(IMethodSymbol symbol)
{
return symbol?.IsInitOnly == true;
}
private void AddPropertyNameAndParameters(IPropertySymbol symbol)
{
bool getMemberNameWithoutInterfaceName = symbol.Name.LastIndexOf('.') > 0;
if (getMemberNameWithoutInterfaceName)
{
AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations);
}
if (symbol.IsIndexer)
{
AddKeyword(SyntaxKind.ThisKeyword);
}
else if (getMemberNameWithoutInterfaceName)
{
this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol,
ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name)));
}
else
{
this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol, symbol.Name));
}
if (this.format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters) && symbol.Parameters.Any())
{
AddPunctuation(SyntaxKind.OpenBracketToken);
AddParametersIfRequired(hasThisParameter: false, isVarargs: false, parameters: symbol.Parameters);
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
public override void VisitEvent(IEventSymbol symbol)
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
var accessor = symbol.AddMethod ?? symbol.RemoveMethod;
if (accessor is object && ShouldMethodDisplayReadOnly(accessor))
{
AddReadOnlyIfRequired();
}
if (format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeMemberKeyword))
{
AddKeyword(SyntaxKind.EventKeyword);
AddSpace();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType))
{
symbol.Type.Accept(this.NotFirstVisitor);
AddSpace();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) &&
IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
AddEventName(symbol);
}
private void AddEventName(IEventSymbol symbol)
{
if (symbol.Name.LastIndexOf('.') > 0)
{
AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations);
this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol,
ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name)));
}
else
{
this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol, symbol.Name));
}
}
public override void VisitMethod(IMethodSymbol symbol)
{
if (symbol.MethodKind == MethodKind.AnonymousFunction)
{
// TODO(cyrusn): Why is this a literal? Why don't we give the appropriate signature
// of the method as asked?
builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, "lambda expression"));
return;
}
else if ((symbol as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SynthesizedGlobalMethodSymbol) // It would be nice to handle VB symbols too, but it's not worth the effort.
{
// Represents a compiler generated synthesized method symbol with a null containing
// type.
// TODO(cyrusn); Why is this a literal?
builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, symbol.Name));
return;
}
else if (symbol.MethodKind == MethodKind.FunctionPointerSignature)
{
visitFunctionPointerSignature(symbol);
return;
}
if (symbol.IsExtensionMethod && format.ExtensionMethodStyle != SymbolDisplayExtensionMethodStyle.Default)
{
if (symbol.MethodKind == MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.StaticMethod)
{
symbol = symbol.GetConstructedReducedFrom();
}
else if (symbol.MethodKind != MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.InstanceMethod)
{
// If we cannot reduce this to an instance form then display in the static form
symbol = symbol.ReduceExtensionMethod(symbol.Parameters.First().Type) ?? symbol;
}
}
// Method members always have a type unless (1) this is a lambda method symbol, which we
// have dealt with already, or (2) this is an error method symbol. If we have an error method
// symbol then we do not know its accessibility, modifiers, etc, all of which require knowing
// the containing type, so we'll skip them.
if ((object)symbol.ContainingType != null || (symbol.ContainingSymbol is ITypeSymbol))
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
if (ShouldMethodDisplayReadOnly(symbol))
{
AddReadOnlyIfRequired();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType))
{
switch (symbol.MethodKind)
{
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
break;
case MethodKind.Destructor:
case MethodKind.Conversion:
// If we're using the metadata format, then include the return type.
// Otherwise we eschew it since it is redundant in a conversion
// signature.
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames))
{
goto default;
}
break;
default:
// The display code is called by the debugger; if a developer is debugging Roslyn and attempts
// to visualize a symbol *during its construction*, the parameters and return type might
// still be null.
if (symbol.ReturnsByRef)
{
AddRefIfRequired();
}
else if (symbol.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
AddCustomModifiersIfRequired(symbol.RefCustomModifiers);
if (symbol.ReturnsVoid)
{
AddKeyword(SyntaxKind.VoidKeyword);
}
else if (symbol.ReturnType != null)
{
AddReturnType(symbol);
}
AddSpace();
AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers);
break;
}
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType))
{
ITypeSymbol containingType;
bool includeType;
if (symbol.MethodKind == MethodKind.LocalFunction)
{
includeType = false;
containingType = null;
}
else if (symbol.MethodKind == MethodKind.ReducedExtension)
{
containingType = symbol.ReceiverType;
includeType = true;
Debug.Assert(containingType != null);
}
else
{
containingType = symbol.ContainingType;
if ((object)containingType != null)
{
includeType = IncludeNamedType(symbol.ContainingType);
}
else
{
containingType = (ITypeSymbol)symbol.ContainingSymbol;
includeType = true;
}
}
if (includeType)
{
containingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
bool isAccessor = false;
switch (symbol.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.DelegateInvoke:
case MethodKind.LocalFunction:
{
//containing type will be the delegate type, name will be Invoke
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name));
break;
}
case MethodKind.ReducedExtension:
{
// Note: Extension methods invoked off of their static class will be tagged as methods.
// This behavior matches the semantic classification done in NameSyntaxClassifier.
builder.Add(CreatePart(SymbolDisplayPartKind.ExtensionMethodName, symbol, symbol.Name));
break;
}
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
{
isAccessor = true;
var associatedProperty = (IPropertySymbol)symbol.AssociatedSymbol;
if (associatedProperty == null)
{
goto case MethodKind.Ordinary;
}
AddPropertyNameAndParameters(associatedProperty);
AddPunctuation(SyntaxKind.DotToken);
AddKeyword(symbol.MethodKind == MethodKind.PropertyGet ? SyntaxKind.GetKeyword :
IsInitOnly(symbol) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword);
break;
}
case MethodKind.EventAdd:
case MethodKind.EventRemove:
{
isAccessor = true;
var associatedEvent = (IEventSymbol)symbol.AssociatedSymbol;
if (associatedEvent == null)
{
goto case MethodKind.Ordinary;
}
AddEventName(associatedEvent);
AddPunctuation(SyntaxKind.DotToken);
AddKeyword(symbol.MethodKind == MethodKind.EventAdd ? SyntaxKind.AddKeyword : SyntaxKind.RemoveKeyword);
break;
}
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
{
// Note: we are using the metadata name also in the case that
// symbol.containingType is null (which should never be the case here) or is an
// anonymous type (which 'does not have a name').
var name = format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null || symbol.ContainingType.IsAnonymousType
? symbol.Name
: symbol.ContainingType.Name;
var partKind = GetPartKindForConstructorOrDestructor(symbol);
builder.Add(CreatePart(partKind, symbol, name));
break;
}
case MethodKind.Destructor:
{
var partKind = GetPartKindForConstructorOrDestructor(symbol);
// Note: we are using the metadata name also in the case that symbol.containingType is null, which should never be the case here.
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null)
{
builder.Add(CreatePart(partKind, symbol, symbol.Name));
}
else
{
AddPunctuation(SyntaxKind.TildeToken);
builder.Add(CreatePart(partKind, symbol, symbol.ContainingType.Name));
}
break;
}
case MethodKind.ExplicitInterfaceImplementation:
{
AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations);
if (!format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) &&
symbol.GetSymbol()?.OriginalDefinition is SourceUserDefinedOperatorSymbolBase sourceUserDefinedOperatorSymbolBase)
{
var operatorName = symbol.MetadataName;
var lastDotPosition = operatorName.LastIndexOf('.');
if (lastDotPosition >= 0)
{
operatorName = operatorName.Substring(lastDotPosition + 1);
}
if (sourceUserDefinedOperatorSymbolBase is SourceUserDefinedConversionSymbol)
{
addUserDefinedConversionName(symbol, operatorName);
}
else
{
addUserDefinedOperatorName(symbol, operatorName);
}
break;
}
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol,
ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name)));
break;
}
case MethodKind.UserDefinedOperator:
case MethodKind.BuiltinOperator:
{
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames))
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName));
}
else
{
addUserDefinedOperatorName(symbol, symbol.MetadataName);
}
break;
}
case MethodKind.Conversion:
{
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames))
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName));
}
else
{
addUserDefinedConversionName(symbol, symbol.MetadataName);
}
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(symbol.MethodKind);
}
if (!isAccessor)
{
AddTypeArguments(symbol, default(ImmutableArray<ImmutableArray<CustomModifier>>));
AddParameters(symbol);
AddTypeParameterConstraints(symbol);
}
void visitFunctionPointerSignature(IMethodSymbol symbol)
{
AddKeyword(SyntaxKind.DelegateKeyword);
AddPunctuation(SyntaxKind.AsteriskToken);
if (symbol.CallingConvention != SignatureCallingConvention.Default)
{
AddSpace();
AddKeyword(SyntaxKind.UnmanagedKeyword);
var conventionTypes = symbol.UnmanagedCallingConventionTypes;
if (symbol.CallingConvention != SignatureCallingConvention.Unmanaged || !conventionTypes.IsEmpty)
{
AddPunctuation(SyntaxKind.OpenBracketToken);
switch (symbol.CallingConvention)
{
case SignatureCallingConvention.CDecl:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Cdecl"));
break;
case SignatureCallingConvention.StdCall:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Stdcall"));
break;
case SignatureCallingConvention.ThisCall:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Thiscall"));
break;
case SignatureCallingConvention.FastCall:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Fastcall"));
break;
case SignatureCallingConvention.Unmanaged:
Debug.Assert(!conventionTypes.IsDefaultOrEmpty);
bool isFirst = true;
foreach (var conventionType in conventionTypes)
{
if (!isFirst)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
isFirst = false;
Debug.Assert(conventionType.Name.StartsWith("CallConv"));
const int CallConvLength = 8;
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, conventionType, conventionType.Name[CallConvLength..]));
}
break;
}
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
AddPunctuation(SyntaxKind.LessThanToken);
foreach (var param in symbol.Parameters)
{
AddParameterRefKind(param.RefKind);
AddCustomModifiersIfRequired(param.RefCustomModifiers);
param.Type.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(param.CustomModifiers, leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
if (symbol.ReturnsByRef)
{
AddRef();
}
else if (symbol.ReturnsByRefReadonly)
{
AddRefReadonly();
}
AddCustomModifiersIfRequired(symbol.RefCustomModifiers);
symbol.ReturnType.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers, leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.GreaterThanToken);
}
void addUserDefinedOperatorName(IMethodSymbol symbol, string operatorName)
{
AddKeyword(SyntaxKind.OperatorKeyword);
AddSpace();
if (operatorName == WellKnownMemberNames.TrueOperatorName)
{
AddKeyword(SyntaxKind.TrueKeyword);
}
else if (operatorName == WellKnownMemberNames.FalseOperatorName)
{
AddKeyword(SyntaxKind.FalseKeyword);
}
else
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName))));
}
}
void addUserDefinedConversionName(IMethodSymbol symbol, string operatorName)
{
// "System.IntPtr.explicit operator System.IntPtr(int)"
if (operatorName == WellKnownMemberNames.ExplicitConversionName)
{
AddKeyword(SyntaxKind.ExplicitKeyword);
}
else if (operatorName == WellKnownMemberNames.ImplicitConversionName)
{
AddKeyword(SyntaxKind.ImplicitKeyword);
}
else
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName))));
}
AddSpace();
AddKeyword(SyntaxKind.OperatorKeyword);
AddSpace();
AddReturnType(symbol);
}
}
private static SymbolDisplayPartKind GetPartKindForConstructorOrDestructor(IMethodSymbol symbol)
{
// In the case that symbol.containingType is null (which should never be the case here) we will fallback to the MethodName symbol part
if (symbol.ContainingType is null)
{
return SymbolDisplayPartKind.MethodName;
}
return GetPartKind(symbol.ContainingType);
}
private void AddReturnType(IMethodSymbol symbol)
{
symbol.ReturnType.Accept(this.NotFirstVisitor);
}
private void AddTypeParameterConstraints(IMethodSymbol symbol)
{
if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints))
{
AddTypeParameterConstraints(symbol.TypeArguments);
}
}
private void AddParameters(IMethodSymbol symbol)
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters))
{
AddPunctuation(SyntaxKind.OpenParenToken);
AddParametersIfRequired(
hasThisParameter: symbol.IsExtensionMethod && symbol.MethodKind != MethodKind.ReducedExtension,
isVarargs: symbol.IsVararg,
parameters: symbol.Parameters);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
public override void VisitParameter(IParameterSymbol symbol)
{
// Note the asymmetry between VisitParameter and VisitTypeParameter: VisitParameter
// decorates the parameter, whereas VisitTypeParameter leaves that to the corresponding
// type or method. This is because type parameters are frequently used in other contexts
// (e.g. field types, param types, etc), which just want the name whereas parameters are
// used on their own or in the context of methods.
var includeType = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeType);
var includeName = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) &&
symbol.Name.Length != 0;
var includeBrackets = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeOptionalBrackets);
var includeDefaultValue = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeDefaultValue) &&
format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) &&
symbol.HasExplicitDefaultValue &&
CanAddConstant(symbol.Type, symbol.ExplicitDefaultValue);
if (includeBrackets && symbol.IsOptional)
{
AddPunctuation(SyntaxKind.OpenBracketToken);
}
if (includeType)
{
AddParameterRefKindIfRequired(symbol.RefKind);
AddCustomModifiersIfRequired(symbol.RefCustomModifiers, leadingSpace: false, trailingSpace: true);
if (symbol.IsParams && format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut))
{
AddKeyword(SyntaxKind.ParamsKeyword);
AddSpace();
}
symbol.Type.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true, trailingSpace: false);
}
if (includeName)
{
if (includeType)
{
AddSpace();
}
var kind = symbol.IsThis ? SymbolDisplayPartKind.Keyword : SymbolDisplayPartKind.ParameterName;
builder.Add(CreatePart(kind, symbol, symbol.Name));
}
if (includeDefaultValue)
{
if (includeName || includeType)
{
AddSpace();
}
AddPunctuation(SyntaxKind.EqualsToken);
AddSpace();
AddConstantValue(symbol.Type, symbol.ExplicitDefaultValue);
}
if (includeBrackets && symbol.IsOptional)
{
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private static bool CanAddConstant(ITypeSymbol type, object value)
{
if (type.TypeKind == TypeKind.Enum)
{
return true;
}
if (value == null)
{
return true;
}
return value.GetType().GetTypeInfo().IsPrimitive || value is string || value is decimal;
}
private void AddFieldModifiersIfRequired(IFieldSymbol symbol)
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) &&
!IsEnumMember(symbol))
{
if (symbol.IsConst)
{
AddKeyword(SyntaxKind.ConstKeyword);
AddSpace();
}
if (symbol.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
if (symbol.IsVolatile)
{
AddKeyword(SyntaxKind.VolatileKeyword);
AddSpace();
}
//TODO: event
}
}
private void AddMemberModifiersIfRequired(ISymbol symbol)
{
INamedTypeSymbol containingType = symbol.ContainingType;
// all members (that end up here) must have a containing type or a containing symbol should be a TypeSymbol.
Debug.Assert(containingType != null || (symbol.ContainingSymbol is ITypeSymbol));
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) &&
(containingType == null ||
(containingType.TypeKind != TypeKind.Interface && !IsEnumMember(symbol) && !IsLocalFunction(symbol))))
{
var isConst = symbol is IFieldSymbol && ((IFieldSymbol)symbol).IsConst;
if (symbol.IsStatic && !isConst)
{
AddKeyword(SyntaxKind.StaticKeyword);
AddSpace();
}
if (symbol.IsOverride)
{
AddKeyword(SyntaxKind.OverrideKeyword);
AddSpace();
}
if (symbol.IsAbstract)
{
AddKeyword(SyntaxKind.AbstractKeyword);
AddSpace();
}
if (symbol.IsSealed)
{
AddKeyword(SyntaxKind.SealedKeyword);
AddSpace();
}
if (symbol.IsExtern)
{
AddKeyword(SyntaxKind.ExternKeyword);
AddSpace();
}
if (symbol.IsVirtual)
{
AddKeyword(SyntaxKind.VirtualKeyword);
AddSpace();
}
}
}
private void AddParametersIfRequired(bool hasThisParameter, bool isVarargs, ImmutableArray<IParameterSymbol> parameters)
{
if (format.ParameterOptions == SymbolDisplayParameterOptions.None)
{
return;
}
var first = true;
// The display code is called by the debugger; if a developer is debugging Roslyn and attempts
// to visualize a symbol *during its construction*, the parameters and return type might
// still be null.
if (!parameters.IsDefault)
{
foreach (var param in parameters)
{
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
else if (hasThisParameter)
{
if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeExtensionThis))
{
AddKeyword(SyntaxKind.ThisKeyword);
AddSpace();
}
}
first = false;
param.Accept(this.NotFirstVisitor);
}
}
if (isVarargs)
{
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
AddKeyword(SyntaxKind.ArgListKeyword);
}
}
private void AddAccessor(IPropertySymbol property, IMethodSymbol method, SyntaxKind keyword)
{
if (method != null)
{
AddSpace();
if (method.DeclaredAccessibility != property.DeclaredAccessibility)
{
AddAccessibility(method);
}
if (!ShouldPropertyDisplayReadOnly(property) && ShouldMethodDisplayReadOnly(method, property))
{
AddReadOnlyIfRequired();
}
AddKeyword(keyword);
AddPunctuation(SyntaxKind.SemicolonToken);
}
}
private void AddExplicitInterfaceIfRequired<T>(ImmutableArray<T> implementedMembers) where T : ISymbol
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeExplicitInterface) && !implementedMembers.IsEmpty)
{
var implementedMember = implementedMembers[0];
Debug.Assert(implementedMember.ContainingType != null);
INamedTypeSymbol containingType = implementedMember.ContainingType;
if (containingType != null)
{
containingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
private void AddCustomModifiersIfRequired(ImmutableArray<CustomModifier> customModifiers, bool leadingSpace = false, bool trailingSpace = true)
{
if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers) && !customModifiers.IsEmpty)
{
bool first = true;
foreach (CustomModifier customModifier in customModifiers)
{
if (!first || leadingSpace)
{
AddSpace();
}
first = false;
this.builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, null, customModifier.IsOptional ? IL_KEYWORD_MODOPT : IL_KEYWORD_MODREQ));
AddPunctuation(SyntaxKind.OpenParenToken);
customModifier.Modifier.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.CloseParenToken);
}
if (trailingSpace)
{
AddSpace();
}
}
}
private void AddRefIfRequired()
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef))
{
AddRef();
}
}
private void AddRef()
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
}
private void AddRefReadonlyIfRequired()
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef))
{
AddRefReadonly();
}
}
private void AddRefReadonly()
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
private void AddReadOnlyIfRequired()
{
// 'readonly' in this context is effectively a 'ref' modifier
// because it affects whether the 'this' parameter is 'ref' or 'in'.
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef))
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
}
private void AddParameterRefKindIfRequired(RefKind refKind)
{
if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut))
{
AddParameterRefKind(refKind);
}
}
private void AddParameterRefKind(RefKind refKind)
{
switch (refKind)
{
case RefKind.Out:
AddKeyword(SyntaxKind.OutKeyword);
AddSpace();
break;
case RefKind.Ref:
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
break;
case RefKind.In:
AddKeyword(SyntaxKind.InKeyword);
AddSpace();
break;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal partial class SymbolDisplayVisitor
{
private const string IL_KEYWORD_MODOPT = "modopt";
private const string IL_KEYWORD_MODREQ = "modreq";
private void VisitFieldType(IFieldSymbol symbol)
{
symbol.Type.Accept(this.NotFirstVisitor);
}
public override void VisitField(IFieldSymbol symbol)
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
AddFieldModifiersIfRequired(symbol);
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType) &&
this.isFirstSymbolVisited &&
!IsEnumMember(symbol))
{
VisitFieldType(symbol);
AddSpace();
AddCustomModifiersIfRequired(symbol.CustomModifiers);
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) &&
IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
if (symbol.ContainingType.TypeKind == TypeKind.Enum)
{
builder.Add(CreatePart(SymbolDisplayPartKind.EnumMemberName, symbol, symbol.Name));
}
else if (symbol.IsConst)
{
builder.Add(CreatePart(SymbolDisplayPartKind.ConstantName, symbol, symbol.Name));
}
else
{
builder.Add(CreatePart(SymbolDisplayPartKind.FieldName, symbol, symbol.Name));
}
if (this.isFirstSymbolVisited &&
format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeConstantValue) &&
symbol.IsConst &&
symbol.HasConstantValue &&
CanAddConstant(symbol.Type, symbol.ConstantValue))
{
AddSpace();
AddPunctuation(SyntaxKind.EqualsToken);
AddSpace();
AddConstantValue(symbol.Type, symbol.ConstantValue, preferNumericValueOrExpandedFlagsForEnum: IsEnumMember(symbol));
}
}
private static bool ShouldPropertyDisplayReadOnly(IPropertySymbol property)
{
if (property.ContainingType?.IsReadOnly == true)
{
return false;
}
// If at least one accessor is present and all present accessors are readonly, the property should be marked readonly.
var getMethod = property.GetMethod;
if (getMethod is object && !ShouldMethodDisplayReadOnly(getMethod, property))
{
return false;
}
var setMethod = property.SetMethod;
if (setMethod is object && !ShouldMethodDisplayReadOnly(setMethod, property))
{
return false;
}
return getMethod is object || setMethod is object;
}
private static bool ShouldMethodDisplayReadOnly(IMethodSymbol method, IPropertySymbol propertyOpt = null)
{
if (method.ContainingType?.IsReadOnly == true)
{
return false;
}
if ((method as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SourcePropertyAccessorSymbol sourceAccessor &&
(propertyOpt as Symbols.PublicModel.PropertySymbol)?.UnderlyingSymbol is SourcePropertySymbolBase sourceProperty)
{
// only display if the accessor is explicitly readonly
return sourceAccessor.LocalDeclaredReadOnly || sourceProperty.HasReadOnlyModifier;
}
else if (method is Symbols.PublicModel.MethodSymbol m)
{
return m.UnderlyingMethodSymbol.IsDeclaredReadOnly;
}
return false;
}
public override void VisitProperty(IPropertySymbol symbol)
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
if (ShouldPropertyDisplayReadOnly(symbol))
{
AddReadOnlyIfRequired();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType))
{
if (symbol.ReturnsByRef)
{
AddRefIfRequired();
}
else if (symbol.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
AddCustomModifiersIfRequired(symbol.RefCustomModifiers);
symbol.Type.Accept(this.NotFirstVisitor);
AddSpace();
AddCustomModifiersIfRequired(symbol.TypeCustomModifiers);
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) &&
IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
AddPropertyNameAndParameters(symbol);
if (format.PropertyStyle == SymbolDisplayPropertyStyle.ShowReadWriteDescriptor)
{
AddSpace();
AddPunctuation(SyntaxKind.OpenBraceToken);
AddAccessor(symbol, symbol.GetMethod, SyntaxKind.GetKeyword);
var keywordForSetAccessor = IsInitOnly(symbol.SetMethod) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword;
AddAccessor(symbol, symbol.SetMethod, keywordForSetAccessor);
AddSpace();
AddPunctuation(SyntaxKind.CloseBraceToken);
}
}
private static bool IsInitOnly(IMethodSymbol symbol)
{
return symbol?.IsInitOnly == true;
}
private void AddPropertyNameAndParameters(IPropertySymbol symbol)
{
bool getMemberNameWithoutInterfaceName = symbol.Name.LastIndexOf('.') > 0;
if (getMemberNameWithoutInterfaceName)
{
AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations);
}
if (symbol.IsIndexer)
{
AddKeyword(SyntaxKind.ThisKeyword);
}
else if (getMemberNameWithoutInterfaceName)
{
this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol,
ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name)));
}
else
{
this.builder.Add(CreatePart(SymbolDisplayPartKind.PropertyName, symbol, symbol.Name));
}
if (this.format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters) && symbol.Parameters.Any())
{
AddPunctuation(SyntaxKind.OpenBracketToken);
AddParametersIfRequired(hasThisParameter: false, isVarargs: false, parameters: symbol.Parameters);
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
public override void VisitEvent(IEventSymbol symbol)
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
var accessor = symbol.AddMethod ?? symbol.RemoveMethod;
if (accessor is object && ShouldMethodDisplayReadOnly(accessor))
{
AddReadOnlyIfRequired();
}
if (format.KindOptions.IncludesOption(SymbolDisplayKindOptions.IncludeMemberKeyword))
{
AddKeyword(SyntaxKind.EventKeyword);
AddSpace();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType))
{
symbol.Type.Accept(this.NotFirstVisitor);
AddSpace();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType) &&
IncludeNamedType(symbol.ContainingType))
{
symbol.ContainingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
AddEventName(symbol);
}
private void AddEventName(IEventSymbol symbol)
{
if (symbol.Name.LastIndexOf('.') > 0)
{
AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations);
this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol,
ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name)));
}
else
{
this.builder.Add(CreatePart(SymbolDisplayPartKind.EventName, symbol, symbol.Name));
}
}
public override void VisitMethod(IMethodSymbol symbol)
{
if (symbol.MethodKind == MethodKind.AnonymousFunction)
{
// TODO(cyrusn): Why is this a literal? Why don't we give the appropriate signature
// of the method as asked?
builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, "lambda expression"));
return;
}
else if ((symbol as Symbols.PublicModel.MethodSymbol)?.UnderlyingMethodSymbol is SynthesizedGlobalMethodSymbol) // It would be nice to handle VB symbols too, but it's not worth the effort.
{
// Represents a compiler generated synthesized method symbol with a null containing
// type.
// TODO(cyrusn); Why is this a literal?
builder.Add(CreatePart(SymbolDisplayPartKind.NumericLiteral, symbol, symbol.Name));
return;
}
else if (symbol.MethodKind == MethodKind.FunctionPointerSignature)
{
visitFunctionPointerSignature(symbol);
return;
}
if (symbol.IsExtensionMethod && format.ExtensionMethodStyle != SymbolDisplayExtensionMethodStyle.Default)
{
if (symbol.MethodKind == MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.StaticMethod)
{
symbol = symbol.GetConstructedReducedFrom();
}
else if (symbol.MethodKind != MethodKind.ReducedExtension && format.ExtensionMethodStyle == SymbolDisplayExtensionMethodStyle.InstanceMethod)
{
// If we cannot reduce this to an instance form then display in the static form
symbol = symbol.ReduceExtensionMethod(symbol.Parameters.First().Type) ?? symbol;
}
}
// Method members always have a type unless (1) this is a lambda method symbol, which we
// have dealt with already, or (2) this is an error method symbol. If we have an error method
// symbol then we do not know its accessibility, modifiers, etc, all of which require knowing
// the containing type, so we'll skip them.
if ((object)symbol.ContainingType != null || (symbol.ContainingSymbol is ITypeSymbol))
{
AddAccessibilityIfRequired(symbol);
AddMemberModifiersIfRequired(symbol);
if (ShouldMethodDisplayReadOnly(symbol))
{
AddReadOnlyIfRequired();
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeType))
{
switch (symbol.MethodKind)
{
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
break;
case MethodKind.Destructor:
case MethodKind.Conversion:
// If we're using the metadata format, then include the return type.
// Otherwise we eschew it since it is redundant in a conversion
// signature.
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames))
{
goto default;
}
break;
default:
// The display code is called by the debugger; if a developer is debugging Roslyn and attempts
// to visualize a symbol *during its construction*, the parameters and return type might
// still be null.
if (symbol.ReturnsByRef)
{
AddRefIfRequired();
}
else if (symbol.ReturnsByRefReadonly)
{
AddRefReadonlyIfRequired();
}
AddCustomModifiersIfRequired(symbol.RefCustomModifiers);
if (symbol.ReturnsVoid)
{
AddKeyword(SyntaxKind.VoidKeyword);
}
else if (symbol.ReturnType != null)
{
AddReturnType(symbol);
}
AddSpace();
AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers);
break;
}
}
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeContainingType))
{
ITypeSymbol containingType;
bool includeType;
if (symbol.MethodKind == MethodKind.LocalFunction)
{
includeType = false;
containingType = null;
}
else if (symbol.MethodKind == MethodKind.ReducedExtension)
{
containingType = symbol.ReceiverType;
includeType = true;
Debug.Assert(containingType != null);
}
else
{
containingType = symbol.ContainingType;
if ((object)containingType != null)
{
includeType = IncludeNamedType(symbol.ContainingType);
}
else
{
containingType = (ITypeSymbol)symbol.ContainingSymbol;
includeType = true;
}
}
if (includeType)
{
containingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
bool isAccessor = false;
switch (symbol.MethodKind)
{
case MethodKind.Ordinary:
case MethodKind.DelegateInvoke:
case MethodKind.LocalFunction:
{
//containing type will be the delegate type, name will be Invoke
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.Name));
break;
}
case MethodKind.ReducedExtension:
{
// Note: Extension methods invoked off of their static class will be tagged as methods.
// This behavior matches the semantic classification done in NameSyntaxClassifier.
builder.Add(CreatePart(SymbolDisplayPartKind.ExtensionMethodName, symbol, symbol.Name));
break;
}
case MethodKind.PropertyGet:
case MethodKind.PropertySet:
{
isAccessor = true;
var associatedProperty = (IPropertySymbol)symbol.AssociatedSymbol;
if (associatedProperty == null)
{
goto case MethodKind.Ordinary;
}
AddPropertyNameAndParameters(associatedProperty);
AddPunctuation(SyntaxKind.DotToken);
AddKeyword(symbol.MethodKind == MethodKind.PropertyGet ? SyntaxKind.GetKeyword :
IsInitOnly(symbol) ? SyntaxKind.InitKeyword : SyntaxKind.SetKeyword);
break;
}
case MethodKind.EventAdd:
case MethodKind.EventRemove:
{
isAccessor = true;
var associatedEvent = (IEventSymbol)symbol.AssociatedSymbol;
if (associatedEvent == null)
{
goto case MethodKind.Ordinary;
}
AddEventName(associatedEvent);
AddPunctuation(SyntaxKind.DotToken);
AddKeyword(symbol.MethodKind == MethodKind.EventAdd ? SyntaxKind.AddKeyword : SyntaxKind.RemoveKeyword);
break;
}
case MethodKind.Constructor:
case MethodKind.StaticConstructor:
{
// Note: we are using the metadata name also in the case that
// symbol.containingType is null (which should never be the case here) or is an
// anonymous type (which 'does not have a name').
var name = format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null || symbol.ContainingType.IsAnonymousType
? symbol.Name
: symbol.ContainingType.Name;
var partKind = GetPartKindForConstructorOrDestructor(symbol);
builder.Add(CreatePart(partKind, symbol, name));
break;
}
case MethodKind.Destructor:
{
var partKind = GetPartKindForConstructorOrDestructor(symbol);
// Note: we are using the metadata name also in the case that symbol.containingType is null, which should never be the case here.
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) || symbol.ContainingType == null)
{
builder.Add(CreatePart(partKind, symbol, symbol.Name));
}
else
{
AddPunctuation(SyntaxKind.TildeToken);
builder.Add(CreatePart(partKind, symbol, symbol.ContainingType.Name));
}
break;
}
case MethodKind.ExplicitInterfaceImplementation:
{
AddExplicitInterfaceIfRequired(symbol.ExplicitInterfaceImplementations);
if (!format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames) &&
symbol.GetSymbol()?.OriginalDefinition is SourceUserDefinedOperatorSymbolBase sourceUserDefinedOperatorSymbolBase)
{
var operatorName = symbol.MetadataName;
var lastDotPosition = operatorName.LastIndexOf('.');
if (lastDotPosition >= 0)
{
operatorName = operatorName.Substring(lastDotPosition + 1);
}
if (sourceUserDefinedOperatorSymbolBase is SourceUserDefinedConversionSymbol)
{
addUserDefinedConversionName(symbol, operatorName);
}
else
{
addUserDefinedOperatorName(symbol, operatorName);
}
break;
}
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol,
ExplicitInterfaceHelpers.GetMemberNameWithoutInterfaceName(symbol.Name)));
break;
}
case MethodKind.UserDefinedOperator:
case MethodKind.BuiltinOperator:
{
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames))
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName));
}
else
{
addUserDefinedOperatorName(symbol, symbol.MetadataName);
}
break;
}
case MethodKind.Conversion:
{
if (format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames))
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol, symbol.MetadataName));
}
else
{
addUserDefinedConversionName(symbol, symbol.MetadataName);
}
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(symbol.MethodKind);
}
if (!isAccessor)
{
AddTypeArguments(symbol, default(ImmutableArray<ImmutableArray<CustomModifier>>));
AddParameters(symbol);
AddTypeParameterConstraints(symbol);
}
void visitFunctionPointerSignature(IMethodSymbol symbol)
{
AddKeyword(SyntaxKind.DelegateKeyword);
AddPunctuation(SyntaxKind.AsteriskToken);
if (symbol.CallingConvention != SignatureCallingConvention.Default)
{
AddSpace();
AddKeyword(SyntaxKind.UnmanagedKeyword);
var conventionTypes = symbol.UnmanagedCallingConventionTypes;
if (symbol.CallingConvention != SignatureCallingConvention.Unmanaged || !conventionTypes.IsEmpty)
{
AddPunctuation(SyntaxKind.OpenBracketToken);
switch (symbol.CallingConvention)
{
case SignatureCallingConvention.CDecl:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Cdecl"));
break;
case SignatureCallingConvention.StdCall:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Stdcall"));
break;
case SignatureCallingConvention.ThisCall:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Thiscall"));
break;
case SignatureCallingConvention.FastCall:
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, symbol, "Fastcall"));
break;
case SignatureCallingConvention.Unmanaged:
Debug.Assert(!conventionTypes.IsDefaultOrEmpty);
bool isFirst = true;
foreach (var conventionType in conventionTypes)
{
if (!isFirst)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
isFirst = false;
Debug.Assert(conventionType.Name.StartsWith("CallConv"));
const int CallConvLength = 8;
builder.Add(CreatePart(SymbolDisplayPartKind.ClassName, conventionType, conventionType.Name[CallConvLength..]));
}
break;
}
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
AddPunctuation(SyntaxKind.LessThanToken);
foreach (var param in symbol.Parameters)
{
AddParameterRefKind(param.RefKind);
AddCustomModifiersIfRequired(param.RefCustomModifiers);
param.Type.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(param.CustomModifiers, leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
if (symbol.ReturnsByRef)
{
AddRef();
}
else if (symbol.ReturnsByRefReadonly)
{
AddRefReadonly();
}
AddCustomModifiersIfRequired(symbol.RefCustomModifiers);
symbol.ReturnType.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.ReturnTypeCustomModifiers, leadingSpace: true, trailingSpace: false);
AddPunctuation(SyntaxKind.GreaterThanToken);
}
void addUserDefinedOperatorName(IMethodSymbol symbol, string operatorName)
{
AddKeyword(SyntaxKind.OperatorKeyword);
AddSpace();
if (operatorName == WellKnownMemberNames.TrueOperatorName)
{
AddKeyword(SyntaxKind.TrueKeyword);
}
else if (operatorName == WellKnownMemberNames.FalseOperatorName)
{
AddKeyword(SyntaxKind.FalseKeyword);
}
else
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName))));
}
}
void addUserDefinedConversionName(IMethodSymbol symbol, string operatorName)
{
// "System.IntPtr.explicit operator System.IntPtr(int)"
if (operatorName == WellKnownMemberNames.ExplicitConversionName)
{
AddKeyword(SyntaxKind.ExplicitKeyword);
}
else if (operatorName == WellKnownMemberNames.ImplicitConversionName)
{
AddKeyword(SyntaxKind.ImplicitKeyword);
}
else
{
builder.Add(CreatePart(SymbolDisplayPartKind.MethodName, symbol,
SyntaxFacts.GetText(SyntaxFacts.GetOperatorKind(operatorName))));
}
AddSpace();
AddKeyword(SyntaxKind.OperatorKeyword);
AddSpace();
AddReturnType(symbol);
}
}
private static SymbolDisplayPartKind GetPartKindForConstructorOrDestructor(IMethodSymbol symbol)
{
// In the case that symbol.containingType is null (which should never be the case here) we will fallback to the MethodName symbol part
if (symbol.ContainingType is null)
{
return SymbolDisplayPartKind.MethodName;
}
return GetPartKind(symbol.ContainingType);
}
private void AddReturnType(IMethodSymbol symbol)
{
symbol.ReturnType.Accept(this.NotFirstVisitor);
}
private void AddTypeParameterConstraints(IMethodSymbol symbol)
{
if (format.GenericsOptions.IncludesOption(SymbolDisplayGenericsOptions.IncludeTypeConstraints))
{
AddTypeParameterConstraints(symbol.TypeArguments);
}
}
private void AddParameters(IMethodSymbol symbol)
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeParameters))
{
AddPunctuation(SyntaxKind.OpenParenToken);
AddParametersIfRequired(
hasThisParameter: symbol.IsExtensionMethod && symbol.MethodKind != MethodKind.ReducedExtension,
isVarargs: symbol.IsVararg,
parameters: symbol.Parameters);
AddPunctuation(SyntaxKind.CloseParenToken);
}
}
public override void VisitParameter(IParameterSymbol symbol)
{
// Note the asymmetry between VisitParameter and VisitTypeParameter: VisitParameter
// decorates the parameter, whereas VisitTypeParameter leaves that to the corresponding
// type or method. This is because type parameters are frequently used in other contexts
// (e.g. field types, param types, etc), which just want the name whereas parameters are
// used on their own or in the context of methods.
var includeType = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeType);
var includeName = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) &&
symbol.Name.Length != 0;
var includeBrackets = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeOptionalBrackets);
var includeDefaultValue = format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeDefaultValue) &&
format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeName) &&
symbol.HasExplicitDefaultValue &&
CanAddConstant(symbol.Type, symbol.ExplicitDefaultValue);
if (includeBrackets && symbol.IsOptional)
{
AddPunctuation(SyntaxKind.OpenBracketToken);
}
if (includeType)
{
AddParameterRefKindIfRequired(symbol.RefKind);
AddCustomModifiersIfRequired(symbol.RefCustomModifiers, leadingSpace: false, trailingSpace: true);
if (symbol.IsParams && format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut))
{
AddKeyword(SyntaxKind.ParamsKeyword);
AddSpace();
}
symbol.Type.Accept(this.NotFirstVisitor);
AddCustomModifiersIfRequired(symbol.CustomModifiers, leadingSpace: true, trailingSpace: false);
}
if (includeName)
{
if (includeType)
{
AddSpace();
}
var kind = symbol.IsThis ? SymbolDisplayPartKind.Keyword : SymbolDisplayPartKind.ParameterName;
builder.Add(CreatePart(kind, symbol, symbol.Name));
}
if (includeDefaultValue)
{
if (includeName || includeType)
{
AddSpace();
}
AddPunctuation(SyntaxKind.EqualsToken);
AddSpace();
AddConstantValue(symbol.Type, symbol.ExplicitDefaultValue);
}
if (includeBrackets && symbol.IsOptional)
{
AddPunctuation(SyntaxKind.CloseBracketToken);
}
}
private static bool CanAddConstant(ITypeSymbol type, object value)
{
if (type.TypeKind == TypeKind.Enum)
{
return true;
}
if (value == null)
{
return true;
}
return value.GetType().GetTypeInfo().IsPrimitive || value is string || value is decimal;
}
private void AddFieldModifiersIfRequired(IFieldSymbol symbol)
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) &&
!IsEnumMember(symbol))
{
if (symbol.IsConst)
{
AddKeyword(SyntaxKind.ConstKeyword);
AddSpace();
}
if (symbol.IsReadOnly)
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
if (symbol.IsVolatile)
{
AddKeyword(SyntaxKind.VolatileKeyword);
AddSpace();
}
//TODO: event
}
}
private void AddMemberModifiersIfRequired(ISymbol symbol)
{
INamedTypeSymbol containingType = symbol.ContainingType;
// all members (that end up here) must have a containing type or a containing symbol should be a TypeSymbol.
Debug.Assert(containingType != null || (symbol.ContainingSymbol is ITypeSymbol));
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeModifiers) &&
(containingType == null ||
(containingType.TypeKind != TypeKind.Interface && !IsEnumMember(symbol) && !IsLocalFunction(symbol))))
{
var isConst = symbol is IFieldSymbol && ((IFieldSymbol)symbol).IsConst;
if (symbol.IsStatic && !isConst)
{
AddKeyword(SyntaxKind.StaticKeyword);
AddSpace();
}
if (symbol.IsOverride)
{
AddKeyword(SyntaxKind.OverrideKeyword);
AddSpace();
}
if (symbol.IsAbstract)
{
AddKeyword(SyntaxKind.AbstractKeyword);
AddSpace();
}
if (symbol.IsSealed)
{
AddKeyword(SyntaxKind.SealedKeyword);
AddSpace();
}
if (symbol.IsExtern)
{
AddKeyword(SyntaxKind.ExternKeyword);
AddSpace();
}
if (symbol.IsVirtual)
{
AddKeyword(SyntaxKind.VirtualKeyword);
AddSpace();
}
}
}
private void AddParametersIfRequired(bool hasThisParameter, bool isVarargs, ImmutableArray<IParameterSymbol> parameters)
{
if (format.ParameterOptions == SymbolDisplayParameterOptions.None)
{
return;
}
var first = true;
// The display code is called by the debugger; if a developer is debugging Roslyn and attempts
// to visualize a symbol *during its construction*, the parameters and return type might
// still be null.
if (!parameters.IsDefault)
{
foreach (var param in parameters)
{
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
else if (hasThisParameter)
{
if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeExtensionThis))
{
AddKeyword(SyntaxKind.ThisKeyword);
AddSpace();
}
}
first = false;
param.Accept(this.NotFirstVisitor);
}
}
if (isVarargs)
{
if (!first)
{
AddPunctuation(SyntaxKind.CommaToken);
AddSpace();
}
AddKeyword(SyntaxKind.ArgListKeyword);
}
}
private void AddAccessor(IPropertySymbol property, IMethodSymbol method, SyntaxKind keyword)
{
if (method != null)
{
AddSpace();
if (method.DeclaredAccessibility != property.DeclaredAccessibility)
{
AddAccessibility(method);
}
if (!ShouldPropertyDisplayReadOnly(property) && ShouldMethodDisplayReadOnly(method, property))
{
AddReadOnlyIfRequired();
}
AddKeyword(keyword);
AddPunctuation(SyntaxKind.SemicolonToken);
}
}
private void AddExplicitInterfaceIfRequired<T>(ImmutableArray<T> implementedMembers) where T : ISymbol
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeExplicitInterface) && !implementedMembers.IsEmpty)
{
var implementedMember = implementedMembers[0];
Debug.Assert(implementedMember.ContainingType != null);
INamedTypeSymbol containingType = implementedMember.ContainingType;
if (containingType != null)
{
containingType.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.DotToken);
}
}
}
private void AddCustomModifiersIfRequired(ImmutableArray<CustomModifier> customModifiers, bool leadingSpace = false, bool trailingSpace = true)
{
if (this.format.CompilerInternalOptions.IncludesOption(SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers) && !customModifiers.IsEmpty)
{
bool first = true;
foreach (CustomModifier customModifier in customModifiers)
{
if (!first || leadingSpace)
{
AddSpace();
}
first = false;
this.builder.Add(CreatePart(InternalSymbolDisplayPartKind.Other, null, customModifier.IsOptional ? IL_KEYWORD_MODOPT : IL_KEYWORD_MODREQ));
AddPunctuation(SyntaxKind.OpenParenToken);
customModifier.Modifier.Accept(this.NotFirstVisitor);
AddPunctuation(SyntaxKind.CloseParenToken);
}
if (trailingSpace)
{
AddSpace();
}
}
}
private void AddRefIfRequired()
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef))
{
AddRef();
}
}
private void AddRef()
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
}
private void AddRefReadonlyIfRequired()
{
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef))
{
AddRefReadonly();
}
}
private void AddRefReadonly()
{
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
private void AddReadOnlyIfRequired()
{
// 'readonly' in this context is effectively a 'ref' modifier
// because it affects whether the 'this' parameter is 'ref' or 'in'.
if (format.MemberOptions.IncludesOption(SymbolDisplayMemberOptions.IncludeRef))
{
AddKeyword(SyntaxKind.ReadOnlyKeyword);
AddSpace();
}
}
private void AddParameterRefKindIfRequired(RefKind refKind)
{
if (format.ParameterOptions.IncludesOption(SymbolDisplayParameterOptions.IncludeParamsRefOut))
{
AddParameterRefKind(refKind);
}
}
private void AddParameterRefKind(RefKind refKind)
{
switch (refKind)
{
case RefKind.Out:
AddKeyword(SyntaxKind.OutKeyword);
AddSpace();
break;
case RefKind.Ref:
AddKeyword(SyntaxKind.RefKeyword);
AddSpace();
break;
case RefKind.In:
AddKeyword(SyntaxKind.InKeyword);
AddSpace();
break;
}
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Scripting/Core/Hosting/CommandLine/ConsoleIO.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
internal class ConsoleIO
{
public static readonly ConsoleIO Default = new ConsoleIO(Console.Out, Console.Error, Console.In);
public TextWriter Error { get; }
public TextWriter Out { get; }
public TextReader In { get; }
public ConsoleIO(TextWriter output, TextWriter error, TextReader input)
{
Debug.Assert(output != null);
Debug.Assert(input != null);
Out = output;
Error = error;
In = input;
}
public virtual void SetForegroundColor(ConsoleColor consoleColor) => Console.ForegroundColor = consoleColor;
public virtual void ResetColor() => Console.ResetColor();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.IO;
namespace Microsoft.CodeAnalysis.Scripting.Hosting
{
internal class ConsoleIO
{
public static readonly ConsoleIO Default = new ConsoleIO(Console.Out, Console.Error, Console.In);
public TextWriter Error { get; }
public TextWriter Out { get; }
public TextReader In { get; }
public ConsoleIO(TextWriter output, TextWriter error, TextReader input)
{
Debug.Assert(output != null);
Debug.Assert(input != null);
Out = output;
Error = error;
In = input;
}
public virtual void SetForegroundColor(ConsoleColor consoleColor) => Console.ForegroundColor = consoleColor;
public virtual void ResetColor() => Console.ResetColor();
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Analyzers/Core/CodeFixes/AddAccessibilityModifiers/AddAccessibilityModifiersHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers
{
internal static class AddAccessibilityModifiersHelpers
{
public static void UpdateDeclaration(
SyntaxEditor editor, ISymbol symbol, SyntaxNode declaration)
{
Contract.ThrowIfNull(symbol);
var preferredAccessibility = GetPreferredAccessibility(symbol);
// Check to see if we need to add or remove
// If there's a modifier, then we need to remove it, otherwise no modifier, add it.
editor.ReplaceNode(
declaration,
(currentDeclaration, _) => UpdateAccessibility(currentDeclaration, preferredAccessibility));
return;
SyntaxNode UpdateAccessibility(SyntaxNode declaration, Accessibility preferredAccessibility)
{
var generator = editor.Generator;
// If there was accessibility on the member, then remove it. If there was no accessibility, then add
// the preferred accessibility for this member.
return generator.GetAccessibility(declaration) == Accessibility.NotApplicable
? generator.WithAccessibility(declaration, preferredAccessibility)
: generator.WithAccessibility(declaration, Accessibility.NotApplicable);
}
}
private static Accessibility GetPreferredAccessibility(ISymbol symbol)
{
// If we have an overridden member, then if we're adding an accessibility modifier, use the
// accessibility of the member we're overriding as both should be consistent here.
if (symbol.GetOverriddenMember() is { DeclaredAccessibility: var accessibility })
return accessibility;
// Default abstract members to be protected, and virtual members to be public. They can't be private as
// that's not legal. And these are reasonable default values for them.
if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol)
{
if (symbol.IsAbstract)
return Accessibility.Protected;
if (symbol.IsVirtual)
return Accessibility.Public;
}
// Otherwise, default to whatever accessibility no-accessibility means for this member;
return symbol.DeclaredAccessibility;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.AddAccessibilityModifiers
{
internal static class AddAccessibilityModifiersHelpers
{
public static void UpdateDeclaration(
SyntaxEditor editor, ISymbol symbol, SyntaxNode declaration)
{
Contract.ThrowIfNull(symbol);
var preferredAccessibility = GetPreferredAccessibility(symbol);
// Check to see if we need to add or remove
// If there's a modifier, then we need to remove it, otherwise no modifier, add it.
editor.ReplaceNode(
declaration,
(currentDeclaration, _) => UpdateAccessibility(currentDeclaration, preferredAccessibility));
return;
SyntaxNode UpdateAccessibility(SyntaxNode declaration, Accessibility preferredAccessibility)
{
var generator = editor.Generator;
// If there was accessibility on the member, then remove it. If there was no accessibility, then add
// the preferred accessibility for this member.
return generator.GetAccessibility(declaration) == Accessibility.NotApplicable
? generator.WithAccessibility(declaration, preferredAccessibility)
: generator.WithAccessibility(declaration, Accessibility.NotApplicable);
}
}
private static Accessibility GetPreferredAccessibility(ISymbol symbol)
{
// If we have an overridden member, then if we're adding an accessibility modifier, use the
// accessibility of the member we're overriding as both should be consistent here.
if (symbol.GetOverriddenMember() is { DeclaredAccessibility: var accessibility })
return accessibility;
// Default abstract members to be protected, and virtual members to be public. They can't be private as
// that's not legal. And these are reasonable default values for them.
if (symbol is IMethodSymbol or IPropertySymbol or IEventSymbol)
{
if (symbol.IsAbstract)
return Accessibility.Protected;
if (symbol.IsVirtual)
return Accessibility.Public;
}
// Otherwise, default to whatever accessibility no-accessibility means for this member;
return symbol.DeclaredAccessibility;
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Workspaces/Core/Portable/Workspace/Host/DocumentService/Extensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Host
{
internal static class Extensions
{
public static bool CanApplyChange([NotNullWhen(returnValue: true)] this TextDocument? document)
=> document?.State.CanApplyChange() ?? false;
public static bool CanApplyChange([NotNullWhen(returnValue: true)] this TextDocumentState? document)
=> document?.Services.GetService<IDocumentOperationService>()?.CanApplyChange ?? false;
public static bool SupportsDiagnostics([NotNullWhen(returnValue: true)] this TextDocument? document)
=> document?.State.SupportsDiagnostics() ?? false;
public static bool SupportsDiagnostics([NotNullWhen(returnValue: true)] this TextDocumentState? document)
=> document?.Services.GetService<IDocumentOperationService>()?.SupportDiagnostics ?? false;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeAnalysis.Host
{
internal static class Extensions
{
public static bool CanApplyChange([NotNullWhen(returnValue: true)] this TextDocument? document)
=> document?.State.CanApplyChange() ?? false;
public static bool CanApplyChange([NotNullWhen(returnValue: true)] this TextDocumentState? document)
=> document?.Services.GetService<IDocumentOperationService>()?.CanApplyChange ?? false;
public static bool SupportsDiagnostics([NotNullWhen(returnValue: true)] this TextDocument? document)
=> document?.State.SupportsDiagnostics() ?? false;
public static bool SupportsDiagnostics([NotNullWhen(returnValue: true)] this TextDocumentState? document)
=> document?.Services.GetService<IDocumentOperationService>()?.SupportDiagnostics ?? false;
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/CSharpTest/QuickInfo/SemanticQuickInfoSourceTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo
{
public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests
{
private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults)
{
var testDocument = workspace.DocumentWithCursor;
var position = testDocument.CursorPosition.GetValueOrDefault();
var documentId = workspace.GetDocumentId(testDocument);
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
await TestWithOptionsAsync(document, service, position, expectedResults);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document, position))
{
var buffer = testDocument.GetTextBuffer();
using (var edit = buffer.CreateEdit())
{
var currentSnapshot = buffer.CurrentSnapshot;
edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText());
edit.Apply();
}
await TestWithOptionsAsync(document, service, position, expectedResults);
}
}
private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults)
{
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""C#"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{0}
</Document>
</Project>
</Workspace>", SecurityElement.Escape(markup));
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
await TestWithOptionsAsync(Options.Regular, markup, expectedResults);
await TestWithOptionsAsync(Options.Script, markup, expectedResults);
}
private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupWithUsings =
@"using System;
using System.Collections.Generic;
using System.Linq;
" + markup;
await TestAsync(markupWithUsings, expectedResults);
}
private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInClass = "class C { " + markup + " }";
return TestWithUsingsAsync(markupInClass, expectedResults);
}
private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInMethod = "class C { void M() { " + markup + " } }";
return TestWithUsingsAsync(markupInMethod, expectedResults);
}
private static async Task TestWithReferenceAsync(string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults);
}
}
private static async Task TestWithMetadataReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestWithProjectReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestInSameProjectHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected async Task TestInvalidTypeInClassAsync(string code)
{
var codeInClass = "class C { " + code + " }";
await TestAsync(codeInClass);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective()
{
await TestAsync(
@"using $$System;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective2()
{
await TestAsync(
@"using System.Coll$$ections.Generic;",
MainDescription("namespace System.Collections"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective3()
{
await TestAsync(
@"using System.L$$inq;",
MainDescription("namespace System.Linq"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = Sys$$tem.Console;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = System.Con$$sole;",
MainDescription("class System.Console"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias()
{
var markup =
@"using I$$ = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias2()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias3()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo
{
void Goo();
}
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestThis()
{
var markup =
@"
///<summary>summary for Class C</summary>
class C { string M() { return thi$$s.ToString(); } }";
await TestWithUsingsAsync(markup,
MainDescription("class C"),
Documentation("summary for Class C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestClassWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
class C { void M() { $$C obj; } }";
await TestAsync(markup,
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingleLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment
// SingleLine doc comment with leading whitespace
await TestAsync(
@"///<summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with leading whitespace and blank line
await TestAsync(
@"///<summary>Hello!
///</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with '\r' line separators
await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultiLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment
// Multiline doc comment with leading whitespace
await TestAsync(
@"/**<summary>Hello!</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag
await TestAsync(
@"/** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/**
** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with no per-line prefix
await TestAsync(
@"/**
<summary>
Hello!
</summary>
*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with inconsistent per-line prefix
await TestAsync(
@"/**
** <summary>
Hello!</summary>
**
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with closing comment on final line
await TestAsync(
@"/**
<summary>Hello!
</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with '\r' line separators
await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
void M() { M$$() }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInt32()
{
await TestInClassAsync(
@"$$Int32 i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInInt()
{
await TestInClassAsync(
@"$$int i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestString()
{
await TestInClassAsync(
@"$$String s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInString()
{
await TestInClassAsync(
@"$$string s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInStringAtEndOfToken()
{
await TestInClassAsync(
@"string$$ s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBoolean()
{
await TestInClassAsync(
@"$$Boolean b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInBool()
{
await TestInClassAsync(
@"$$bool b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingle()
{
await TestInClassAsync(
@"$$Single s;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInFloat()
{
await TestInClassAsync(
@"$$float f;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVoidIsInvalid()
{
await TestInvalidTypeInClassAsync(
@"$$void M()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer1_931958()
{
await TestInvalidTypeInClassAsync(
@"$$T* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer2_931958()
{
await TestInvalidTypeInClassAsync(
@"T$$* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer3_931958()
{
await TestInvalidTypeInClassAsync(
@"T*$$ i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfString()
{
await TestInClassAsync(
@"$$List<string> l;",
MainDescription("class System.Collections.Generic.List<T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfSomethingFromSource()
{
var markup =
@"
///<summary>Generic List</summary>
public class GenericList<T> { Generic$$List<int> t; }";
await TestAsync(markup,
MainDescription("class GenericList<T>"),
Documentation("Generic List"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfT()
{
await TestInMethodAsync(
@"class C<T>
{
$$List<T> l;
}",
MainDescription("class System.Collections.Generic.List<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfIntAndString()
{
await TestInClassAsync(
@"$$Dictionary<int, string> d;",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} int",
$"TValue {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfTAndU()
{
await TestInMethodAsync(
@"class C<T, U>
{
$$Dictionary<T, U> d;
}",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} T",
$"TValue {FeaturesResources.is_} U")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIEnumerableOfInt()
{
await TestInClassAsync(
@"$$IEnumerable<int> M()
{
yield break;
}",
MainDescription("interface System.Collections.Generic.IEnumerable<out T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventHandler()
{
await TestInClassAsync(
@"event $$EventHandler e;",
MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter()
{
await TestAsync(
@"class C<T>
{
$$T t;
}",
MainDescription($"T {FeaturesResources.in_} C<T>"));
}
[WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
///<typeparam name=""T"">T is Type Parameter</typeparam>
class C<T> { $$T t; }";
await TestAsync(markup,
MainDescription($"T {FeaturesResources.in_} C<T>"),
Documentation("T is Type Parameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter1_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
$$T11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter2_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T$$11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter3_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T1$$1 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter4_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T11$$ t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableOfInt()
{
await TestInClassAsync(@"$$Nullable<int> i; }",
MainDescription("struct System.Nullable<T> where T : struct"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod1_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>($$T1 i) where T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod2_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where $$T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod3_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Class()
{
await TestAsync(
@"class C<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} C<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Struct()
{
await TestAsync(
@"struct S<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} S<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Interface()
{
await TestAsync(
@"interface I<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} I<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Delegate()
{
await TestAsync(
@"delegate void D<T>() where $$T : class;",
MainDescription($"T {FeaturesResources.in_} D<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMinimallyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FullyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethod()
{
await TestAsync(
@"class C
{
void M()
{
M$$();
}
}",
MainDescription("void C.M()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethodWithDocComment()
{
var markup =
@"
///<summary>Hello World</summary>
void M() { M$$(); }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello World"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn()
{
var markup =
@"int field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn2()
{
await TestInClassAsync(
@"int field;
void M()
{
int f = field$$;
}",
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltInWithFieldInitializer()
{
await TestInClassAsync(
@"int field = 1;
void M()
{
int f = field $$;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn()
{
await TestInMethodAsync(
@"int x;
x = x$$+1;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn1()
{
await TestInMethodAsync(
@"int x;
x = x$$ + 1;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn2()
{
await TestInMethodAsync(
@"int x;
x = x+$$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn3()
{
await TestInMethodAsync(
@"int x;
x = x +$$ x;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn4()
{
await TestInMethodAsync(
@"int x;
x = x + $$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeBuiltIn()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
}";
await TestAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeOverload()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
static C operator+(C a, C b) { return a; }
}";
await TestAsync(markup,
MainDescription("C C.operator +(C a, C b)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodMinimal()
{
var markup =
@"DateTime field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodQualified()
{
var markup =
@"System.IO.FileInfo file;
void M()
{
file$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldMinimal()
{
await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified1()
{
// NOTE: we qualify the field type, but not the type that contains the field in Dev10
var markup =
@"class C {
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified2()
{
await TestAsync(
@"class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified3()
{
await TestAsync(
@"using System;
class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
}
class D
{
void M()
{
new C<int>().Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) int C<int>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
void M()
{
Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) T C<T>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIntegerLiteral()
{
await TestInMethodAsync(@"int f = 37$$",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrueKeyword()
{
await TestInMethodAsync(@"bool f = true$$",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFalseKeyword()
{
await TestInMethodAsync(@"bool f = false$$",
MainDescription("struct System.Boolean"));
}
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteral()
{
await TestInMethodAsync(@"string f = null$$",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteralWithVar()
=> await TestInMethodAsync(@"var f = null$$");
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDefaultLiteral()
{
await TestInMethodAsync(@"string f = default$$",
MainDescription("class System.String"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnGenericTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
aw$$ait Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordInDeclarationStatement()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
var x = $$await Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async void Calc()
{
aw$$ait Task.Delay(100);
}
}";
await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords1()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = await awa$$it resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords2()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = awa$$it await resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitablePrefixOnCustomAwaiter()
{
var markup = @"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Z = $$C;
class C
{
public MyAwaiter GetAwaiter() { throw new NotImplementedException(); }
}
class MyAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
throw new NotImplementedException();
}
public bool IsCompleted { get { throw new NotImplementedException(); } }
public void GetResult() { }
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskType()
{
var markup = @"using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$ v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskOfTType()
{
var markup = @"using System;
using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$<int> v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDynamicIsntAwaitable()
{
var markup = @"
class C
{
dynamic D() { return null; }
void M()
{
D$$();
}
}
";
await TestAsync(markup, MainDescription("dynamic C.D()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStringLiteral()
{
await TestInMethodAsync(@"string f = ""Goo""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimStringLiteral()
{
await TestInMethodAsync(@"string f = @""cat""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCharLiteral()
{
await TestInMethodAsync(@"string f = 'x'$$",
MainDescription("struct System.Char"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicKeyword()
{
await TestInMethodAsync(
@"dyn$$amic dyn;",
MainDescription("dynamic"),
Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicField()
{
await TestInClassAsync(
@"dynamic dyn;
void M()
{
d$$yn.Goo();
}",
MainDescription($"({FeaturesResources.field}) dynamic C.dyn"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal()
{
await TestInClassAsync(
@"DateTime Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet()
{
await TestInClassAsync(
@"public DateTime Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet1()
{
await TestInClassAsync(
@"protected internal int Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("int C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Qualified()
{
await TestInClassAsync(
@"System.IO.FileInfo Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("System.IO.FileInfo C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Minimal()
{
await TestInMethodAsync(@"DateTime.No$$w.ToString();",
MainDescription("DateTime DateTime.Now { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo f;
f.Att$$ributes.ToString();",
MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set }
}
class D
{
void M()
{
new C<int>().Pro$$perty.ToString();
}
}",
MainDescription("int C<int>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set}
void M()
{
Pro$$perty.ToString();
}
}",
MainDescription("T C<T>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueInProperty()
{
await TestInClassAsync(
@"public DateTime Property
{
set
{
goo = val$$ue;
}
}",
MainDescription($"({FeaturesResources.parameter}) DateTime value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumTypeName()
{
await TestInMethodAsync(@"Consol$$eColor c",
MainDescription("enum System.ConsoleColor"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_Definition()
{
await TestInClassAsync(@"enum E$$ : byte { A, B }",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsField()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ _E;
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsProperty()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ E{ get; set; };
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsParameter()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M(E$$ e) { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsReturnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ M() { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsLocal()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
E$$ e = default;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E$$.A;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E.A$$;
}
",
MainDescription("E.A = 0"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("byte", "byte")]
[InlineData("byte", "System.Byte")]
[InlineData("sbyte", "sbyte")]
[InlineData("sbyte", "System.SByte")]
[InlineData("short", "short")]
[InlineData("short", "System.Int16")]
[InlineData("ushort", "ushort")]
[InlineData("ushort", "System.UInt16")]
// int is the default type and is not shown
[InlineData("uint", "uint")]
[InlineData("uint", "System.UInt32")]
[InlineData("long", "long")]
[InlineData("long", "System.Int64")]
[InlineData("ulong", "ulong")]
[InlineData("ulong", "System.UInt64")]
public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName)
{
await TestInClassAsync(@$"
enum E$$ : {underlyingTypeName}
{{
A, B
}}",
MainDescription($"enum C.E : {displayTypeName}"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("")]
[InlineData(": int")]
[InlineData(": System.Int32")]
public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType)
{
await TestInClassAsync(@$"
enum E$$ {defaultType}
{{
A, B
}}",
MainDescription("enum C.E"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromMetadata()
{
await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck",
MainDescription("ConsoleColor.Black = 0"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata1()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass",
MainDescription("AttributeTargets.Class = 4"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata2()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll",
MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource1()
{
await TestAsync(
@"enum E
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1 << 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource2()
{
await TestAsync(
@"enum E
{
A,
B,
C
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Minimal()
{
await TestInClassAsync(
@"void M(DateTime dt)
{
d$$t.ToString();",
MainDescription($"({FeaturesResources.parameter}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Qualified()
{
await TestInClassAsync(
@"void M(System.IO.FileInfo fileInfo)
{
file$$Info.ToString();",
MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_FromReferenceToNamedParameter()
{
await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");",
MainDescription($"({FeaturesResources.parameter}) string value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_DefaultValue()
{
// NOTE: Dev10 doesn't show the default value, but it would be nice if we did.
// NOTE: The "DefaultValue" property isn't implemented yet.
await TestInClassAsync(
@"void M(int param = 42)
{
para$$m.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) int param = 42"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Params()
{
await TestInClassAsync(
@"void M(params DateTime[] arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Ref()
{
await TestInClassAsync(
@"void M(ref DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) ref DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Out()
{
await TestInClassAsync(
@"void M(out DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) out DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Minimal()
{
await TestInMethodAsync(
@"DateTime dt;
d$$t.ToString();",
MainDescription($"({FeaturesResources.local_variable}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo fileInfo;
file$$Info.ToString();",
MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MetadataOverload()
{
await TestInMethodAsync("Console.Write$$Line();",
MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleWithOverload()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod();
}
void Method(int i)
{
}",
MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MoreOverloads()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod(null);
}
void Method(int i)
{
}
void Method(DateTime dt)
{
}
void Method(System.IO.FileInfo fileInfo)
{
}",
MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleInSameClass()
{
await TestInClassAsync(
@"DateTime GetDate(System.IO.FileInfo ft)
{
Get$$Date(null);
}",
MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParameter()
{
await TestInClassAsync(
@"void M()
{
Met$$hod();
}
void Method(int i = 0)
{
}",
MainDescription("void C.Method([int i = 0])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalDecimalParameter()
{
await TestInClassAsync(
@"void Goo(decimal x$$yz = 10)
{
}",
MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Generic()
{
// Generic method don't get the instantiation info yet. NOTE: We don't display
// constraint info in Dev10. Should we?
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
Go$$o<int, DateTime>(37);
}",
MainDescription("DateTime C.Goo<int, DateTime>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_UnconstructedGeneric()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg)
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Inferred()
{
await TestInClassAsync(
@"void Goo<TIn>(TIn arg)
{
Go$$o(42);
}",
MainDescription("void C.Goo<int>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MultipleParams()
{
await TestInClassAsync(
@"void Goo(DateTime dt, System.IO.FileInfo fi, int number)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParam()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(int num = 42)
{
Go$$o();
}",
MainDescription("void C.Goo([int num = 42])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_ParameterModifiers()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor()
{
await TestInClassAsync(
@"public C()
{
}
void M()
{
new C$$().ToString();
}",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Overloads()
{
await TestInClassAsync(
@"public C()
{
}
public C(DateTime dt)
{
}
public C(int i)
{
}
void M()
{
new C$$(DateTime.MaxValue).ToString();
}",
MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromStringLiteral()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException("""");",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_UnknownType()
{
await TestInvalidTypeInClassAsync(
@"void M()
{
new G$$oo();
}");
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromProperty()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException(this.GetType().Name);",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Metadata()
{
await TestInMethodAsync(
@"new Argument$$NullException();",
MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_MetadataQualified()
{
await TestInMethodAsync(@"new System.IO.File$$Info(null);",
MainDescription("System.IO.FileInfo.FileInfo(string fileName)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InterfaceProperty()
{
await TestInMethodAsync(
@"interface I
{
string Name$$ { get; set; }
}",
MainDescription("string I.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExplicitInterfacePropertyImplementation()
{
await TestInMethodAsync(
@"interface I
{
string Name { get; set; }
}
class C : I
{
string IEmployee.Name$$
{
get
{
return """";
}
set
{
}
}
}",
MainDescription("string C.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Operator()
{
await TestInClassAsync(
@"public static C operator +(C left, C right)
{
return null;
}
void M(C left, C right)
{
return left +$$ right;
}",
MainDescription("C C.operator +(C left, C right)"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithMultipleConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnConstructedGenericMethodWithConstraintsAtInvocation()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericTypeWithConstraintsAtDeclaration()
{
await TestAsync(
@"public class Employee : IComparable<Employee>
{
public int CompareTo(Employee other)
{
throw new NotImplementedException();
}
}
class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new()
{
}",
MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericType()
{
await TestAsync(
@"class T1<T11>
{
$$T11 i;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethod()
{
await TestInClassAsync(
@"static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Var()
{
await TestInMethodAsync(
@"var x = new Exception();
var y = $$x;",
MainDescription($"({FeaturesResources.local_variable}) Exception x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableReference()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
@"class A<T>
{
}
class B
{
static void M()
{
A<B?>? x = null!;
var y = x;
$$y.ToString();
}
}",
// https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability
MainDescription($"({FeaturesResources.local_variable}) A<B?> y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")]
public async Task NullableReference_InMethod()
{
var code = @"
class G
{
void M()
{
C c;
c.Go$$o();
}
}
public class C
{
public string? Goo(IEnumerable<object?> arg)
{
}
}";
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
code, MainDescription("string? C.Goo(IEnumerable<object?> arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedInGeneric()
{
await TestInMethodAsync(
@"List<int>.Enu$$merator e;",
MainDescription("struct System.Collections.Generic.List<T>.Enumerator"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedGenericInGeneric()
{
await TestAsync(
@"class Outer<T>
{
class Inner<U>
{
}
static void M()
{
Outer<int>.I$$nner<string> e;
}
}",
MainDescription("class Outer<T>.Inner<U>"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"U {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer1()
{
await TestInClassAsync(
@"void M()
{
var x = new test() { $$z = 5 };
}
class test
{
public int z;
}",
MainDescription($"({FeaturesResources.field}) int test.z"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer2()
{
await TestInMethodAsync(
@"class C
{
void M()
{
var x = new test() { z = $$5 };
}
class test
{
public int z;
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")]
public async Task TypeArgument()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
$$variable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ForEachLoop_1()
{
await TestInMethodAsync(
@"int bb = 555;
bb = bb + 1;
foreach (int cc in new int[]{ 1,2,3}){
c$$c = 1;
bb = bb + 21;
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_1()
{
await TestInMethodAsync(
@"try
{
int aa = 555;
a$$a = aa + 1;
}
catch (Exception ex)
{
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_2()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var y = e$$x;
var z = y;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) Exception ex"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_3()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var aa = 555;
aa = a$$a + 1;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_4()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
}
finally
{
int aa = 555;
aa = a$$a + 1;
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericVariable()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
var$$iable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInstantiation()
{
await TestAsync(
@"using System.Collections.Generic;
class Program<T>
{
static void Main(string[] args)
{
var p = new Dictio$$nary<int, string>();
}
}",
MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUsingAlias_Bug4141()
{
await TestAsync(
@"using X = A.C;
class A
{
public class C
{
}
}
class D : X$$
{
}",
MainDescription(@"class A.C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldOnDeclaration()
{
await TestInClassAsync(
@"DateTime fie$$ld;",
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericErrorFieldOnDeclaration()
{
await TestInClassAsync(
@"NonExistentType<int> fi$$eld;",
MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field"));
}
[WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateType()
{
await TestInClassAsync(
@"Fun$$c<int, string> field;",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"TResult {FeaturesResources.is_} string")));
}
[WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnDelegateInvocation()
{
await TestAsync(
@"class Program
{
delegate void D1();
static void Main()
{
D1 d = Main;
$$d();
}
}",
MainDescription($"({FeaturesResources.local_variable}) D1 d"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation1()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = n$$ew int[0];
}
}", MainDescription("int[]"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation2()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = new i$$nt[0];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation()
{
await TestAsync(
@"class C
{
static void Main()
{
C c = ne$$w();
}
}
",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation_WithParameters()
{
await TestAsync(
@"class C
{
C(int i) { }
C(string s) { }
static void Main()
{
C c = ne$$w(1);
}
}
",
MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})"));
}
[WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIsNamedTypeAccessibleForErrorTypes()
{
await TestAsync(
@"sealed class B<T1, T2> : A<B<T1, T2>>
{
protected sealed override B<A<T>, A$$<T>> N()
{
}
}
internal class A<T>
{
}",
MainDescription("class A<T>"));
}
[WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType()
{
await TestAsync(
@"using Goo = Goo;
class C
{
void Main()
{
$$Goo
}
}",
MainDescription("Goo"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
$$_ = M();
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnderscoreLocalInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
var $$_ = M();
}
}",
MainDescription($"({FeaturesResources.local_variable}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out $$_);
i = 0;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out var $$_);
i = 0;
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInIsPattern()
{
await TestAsync(
@"class C
{
void M()
{
if (3 is int $$_) { }
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInSwitchPattern()
{
await TestAsync(
@"class C
{
void M()
{
switch (3)
{
case int $$_:
return;
}
}
}"); // No quick info (see issue #16667)
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_FirstDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = ($$_, _) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) string _"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_SecondDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = (_, $$_) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLiterals()
{
await TestAsync(
@"class MyClass
{
MyClass() : this($$10)
{
intI = 2;
}
public MyClass(int i)
{
}
static int intI = 1;
public static int Main()
{
return 1;
}
}",
MainDescription("struct System.Int32"));
}
[WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorInForeach()
{
await TestAsync(
@"class C
{
void Main()
{
foreach (int cc in null)
{
$$cc = 1;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnEvent()
{
await TestAsync(
@"using System;
public class SampleEventArgs
{
public SampleEventArgs(string s)
{
Text = s;
}
public String Text { get; private set; }
}
public class Publisher
{
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
public event SampleEventHandler SampleEvent;
protected virtual void RaiseSampleEvent()
{
if (Sam$$pleEvent != null)
SampleEvent(this, new SampleEventArgs(""Hello""));
}
}",
MainDescription("SampleEventHandler Publisher.SampleEvent"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEvent()
{
await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;",
MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventPlusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;",
MainDescription("void Console.CancelKeyPress.add"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventMinusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;",
MainDescription("void Console.CancelKeyPress.remove"));
}
[WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethod()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] values = {
1
};
bool isArray = 7.I$$n(values);
}
}
public static class MyExtensions
{
public static bool In<T>(this T o, IEnumerable<T> items)
{
return true;
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this string ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads2()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this int ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query1()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query2()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query3()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query4()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query5()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query6()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query7()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query8()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query9()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x$$ in new List<List<int>>()
from y in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query10()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in $$x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query11()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y$$ in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query12()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in x
select $$y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedEnumerable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedQueryable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0].AsQueryable()
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedCustom()
{
await TestAsync(
@"
using System;
using System.Linq;
namespace N {
public static class LazyExt
{
public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value));
}
public class C
{
public void M()
{
var lazy = new Lazy<object>();
var q = from i in lazy
$$select i;
}
}
}
",
MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectNotMapped()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where true
$$select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoLet()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$let j = true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"),
AnonymousTypes($@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int i, bool j }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoWhere()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$where true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOneProperty()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i$$, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending, i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending ,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByIncomplete()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where i > 0
orderby$$
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$from i2 in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
from i2 $$in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
group i $$by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupByInto()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 $$in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2 into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 equals i2 $$into g
select g;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoFromMissing()
{
await TestInMethodAsync(
@"
var q = $$from i in new int[0]
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple1()
{
await TestInMethodAsync(
@"
var q = $$from double i in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple2()
{
await TestInMethodAsync(
@"
var q = from double i $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$from double d in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
from double d $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join int i2 in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 $$in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorGlobal()
{
await TestAsync(
@"extern alias global;
class myClass
{
static int Main()
{
$$global::otherClass oc = new global::otherClass();
return 0;
}
}",
MainDescription("<global namespace>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1()
{
await TestAsync(
@"using System;
class classAttribute : Attribute
{
private classAttribute x$$;
}",
MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x"));
}
[WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffix2()
{
await TestAsync(
@"using System;
class class1Attribute : Attribute
{
private class1Attribute x$$;
}",
MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeQuickInfoBindsToClassTest()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
[Some$$]
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
}
}",
Documentation("class comment"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeConstructorQuickInfo()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
var s = new Some$$Attribute();
}
}",
Documentation("ctor comment"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLabel()
{
await TestInClassAsync(
@"void M()
{
Goo:
int Goo;
goto Goo$$;
}",
MainDescription($"({FeaturesResources.label}) Goo"));
}
[WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnboundGeneric()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
Type t = typeof(L$$ist<>);
}
}",
MainDescription("class System.Collections.Generic.List<T>"),
NoTypeParameterMap);
}
[WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousTypeNew1()
{
await TestAsync(
@"class C
{
void M()
{
var v = $$new { };
}
}",
MainDescription(@"AnonymousType 'a"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}"));
}
[WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAnonymousType()
{
// verify nested anonymous types are listed in the same order for different properties
// verify first property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Address",
MainDescription(@"'b 'a.Address { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
// verify second property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Name",
MainDescription(@"string 'a.Name { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")]
public async Task TestAssignmentOperatorInAnonymousType()
{
await TestAsync(
@"class C
{
void M()
{
var a = new { A $$= 0 };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(10731, "DevDiv_Projects/Roslyn")]
public async Task TestErrorAnonymousTypeDoesntShow()
{
await TestInMethodAsync(
@"var a = new { new { N = 0 }.N, new { } }.$$N;",
MainDescription(@"int 'a.N { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int N }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")]
public async Task TestArrayAssignedToVar()
{
await TestAsync(
@"class C
{
static void M(string[] args)
{
v$$ar a = args;
}
}",
MainDescription("string[]"));
}
[WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ColorColorRangeVariable()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
namespace N1
{
class yield
{
public static IEnumerable<yield> Bar()
{
foreach (yield yield in from yield in new yield[0]
select y$$ield)
{
yield return yield;
}
}
}
}",
MainDescription($"({FeaturesResources.range_variable}) N1.yield yield"));
}
[WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoOnOperator()
{
await TestAsync(
@"using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var v = new Program() $$+ string.Empty;
}
public static implicit operator Program(string s)
{
return null;
}
public static IEnumerable<Program> operator +(Program p1, Program p2)
{
yield return p1;
yield return p2;
}
}",
MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantField()
{
await TestAsync(
@"class C
{
const int $$F = 1;",
MainDescription($"({FeaturesResources.constant}) int C.F = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultipleConstantFields()
{
await TestAsync(
@"class C
{
public const double X = 1.0, Y = 2.0, $$Z = 3.5;",
MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantDependencies()
{
await TestAsync(
@"class A
{
public const int $$X = B.Z + 1;
public const int Y = 10;
}
class B
{
public const int Z = A.Y + 1;
}",
MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantCircularDependencies()
{
await TestAsync(
@"class A
{
public const int X = B.Z + 1;
}
class B
{
public const int Z$$ = A.X + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflow()
{
await TestAsync(
@"class B
{
public const int Z$$ = int.MaxValue + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflowInUncheckedContext()
{
await TestAsync(
@"class B
{
public const int Z$$ = unchecked(int.MaxValue + 1);
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEnumInConstantField()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const int $$x = (int)Days.Sun;
}
}",
MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantInDefaultExpression()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const Days $$x = default(Days);
}
}",
MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantParameter()
{
await TestAsync(
@"class C
{
void Bar(int $$b = 1);
}",
MainDescription($"({FeaturesResources.parameter}) int b = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantLocal()
{
await TestAsync(
@"class C
{
void Bar()
{
const int $$loc = 1;
}",
MainDescription($"({FeaturesResources.local_constant}) int loc = 1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType1()
{
await TestInMethodAsync(
@"var $$v1 = new Goo();",
MainDescription($"({FeaturesResources.local_variable}) Goo v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType2()
{
await TestInMethodAsync(
@"var $$v1 = v1;",
MainDescription($"({FeaturesResources.local_variable}) var v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType3()
{
await TestInMethodAsync(
@"var $$v1 = new Goo<Bar>();",
MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType4()
{
await TestInMethodAsync(
@"var $$v1 = &(x => x);",
MainDescription($"({FeaturesResources.local_variable}) ?* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType5()
{
await TestInMethodAsync("var $$v1 = &v1",
MainDescription($"({FeaturesResources.local_variable}) var* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType6()
{
await TestInMethodAsync("var $$v1 = new Goo[1]",
MainDescription($"({FeaturesResources.local_variable}) Goo[] v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType7()
{
await TestInClassAsync(
@"class C
{
void Method()
{
}
void Goo()
{
var $$v1 = MethodGroup;
}
}",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType8()
{
await TestInMethodAsync("var $$v1 = Unknown",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateSpecialTypes()
{
await TestAsync(
@"delegate void $$F(int x);",
MainDescription("delegate void F(int x)"));
}
[WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullPointerParameter()
{
await TestAsync(
@"class C
{
unsafe void $$Goo(int* x = null)
{
}
}",
MainDescription("void C.Goo([int* x = null])"));
}
[WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLetIdentifier1()
{
await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableDefaultValue()
{
await TestAsync(
@"class Test
{
void $$Method(int? t1 = null)
{
}
}",
MainDescription("void Test.Method([int? t1 = null])"));
}
[WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidParameterInitializer()
{
await TestAsync(
@"class Program
{
void M1(float $$j1 = ""Hello""
+
""World"")
{
}
}",
MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World"""));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstLocal()
{
await TestAsync(
@"class Program
{
void Main()
{
const int MEGABYTE = 1024 *
1024 + true;
Blah($$MEGABYTE);
}
}",
MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true"));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstField()
{
await TestAsync(
@"class Program
{
const int a = true
-
false;
void Main()
{
Goo($$a);
}
}",
MainDescription($"({FeaturesResources.constant}) int Program.a = true - false"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterCrefDoesNotHaveQuickInfo()
{
await TestAsync(
@"class C<T>
{
/// <see cref=""C{X$$}""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref1()
{
await TestAsync(
@"class Program
{
/// <see cref=""Mai$$n""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref2()
{
await TestAsync(
@"class Program
{
/// <see cref=""$$Main""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref3()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref4()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main$$""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref5()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.Index$$Prop[0] = ""s"";
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await TestWithReferenceAsync(sourceCode: markup,
referencedCode: referencedCode,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }"));
}
[WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGeneric()
{
await TestAsync(
@"class A<T>
{
enum SortOrder
{
Ascending,
Descending,
None
}
void Goo()
{
var b = $$SortOrder.Ascending;
}
}",
MainDescription(@"enum A<T>.SortOrder"));
}
[WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGenericInCRef()
{
await TestAsync(
@"/// <see cref=""$$C{T}"" />
class C<T>
{
}",
MainDescription(@"class C<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitableMethod()
{
var markup = @"using System.Threading.Tasks;
class C
{
async Task Goo()
{
Go$$o();
}
}";
var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()";
await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
go$$o();
}
}";
await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()"));
}
[WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicOperator()
{
var markup = @"
public class Test
{
public delegate void NoParam();
static int Main()
{
dynamic x = new object();
if (((System.Func<dynamic>)(() => (x =$$= null)))())
return 0;
return 1;
}
}";
await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment()
{
await TestAsync(
@"/// <summary>
///goo
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine()
{
await TestAsync(
@"/// <summary>
/// goo
/// bar
/// </summary>
class C$$
{
}", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref()
{
await TestAsync(
@"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
class C$$
{
}", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock()
{
await TestAsync(
@"/// red
/// <summary>
/// green
/// </summary>
/// yellow
class C$$
{
}", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NewlineAfterPara()
{
await TestAsync(
@"/// <summary>
/// <para>goo</para>
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment_Metadata()
{
var referenced = @"
/// <summary>
///goo
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine_Metadata()
{
var referenced = @"
/// <summary>
/// goo
/// bar
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"
/// red
/// <summary>
/// green
/// </summary>
/// yellow
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] arg$$s, T otherParam)
{
}
}", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(arg$$s: new string[] { }, 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T oth$$erParam)
{
}
}", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(args: new string[] { }, other$$Param: 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TypeParam()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnboundCref()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructor()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass$$()
{
}
}", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructorOverloaded()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass()
{
}
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute.
/// </summary>
public TestC$$lass(int value)
{
}
}", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod1()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod2()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading1()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValu$$e();
GetGenericValue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading2()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValue();
GetGenericVal$$ue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericType()
{
await TestAsync(
@"/// <summary>
/// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks>
/// </summary>
class Generic$$Class<T>
{
}",
Documentation("This example shows how to specify the GenericClass<T> cref.",
ExpectedClassifications(
Text("This example shows how to specify the"),
WhiteSpace(" "),
Class("GenericClass"),
Punctuation.OpenAngle,
TypeParameter("T"),
Punctuation.CloseAngle,
WhiteSpace(" "),
Text("cref."))));
}
[WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ClassificationOfCrefsFromMetadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Go$$o();
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <summary>
/// See <see cref=""Goo""/> method
/// </summary>
public void Goo()
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#",
Documentation("See C.Goo() method",
ExpectedClassifications(
Text("See"),
WhiteSpace(" "),
Class("C"),
Punctuation.Text("."),
Identifier("Goo"),
Punctuation.OpenParen,
Punctuation.CloseParen,
WhiteSpace(" "),
Text("method"))));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
int x;
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")]
public async Task BindSymbolInOtherFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage(
$"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}",
expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
x$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NoValidSymbolsInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void goo()
{
B$$ar();
}
#if B
void Bar() { }
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
int x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
#if PROJ1
int x;
#endif
int y = x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
$$LABEL: goto LABEL;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] {1, 2, 3} select $$y;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") });
}
[WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PointerAccessibility()
{
var markup = @"class C
{
unsafe static void Main()
{
void* p = null;
void* q = null;
dynamic d = true;
var x = p =$$= q == d;
}
}";
await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)"));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfArrayType()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int[]> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]")));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfDynamic()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<dynamic> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic")));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do$$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void Shared()
{
var x = GetThing().Do$$();
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")]
public async Task QuickInfoExceptions()
{
await TestAsync(
@"using System;
namespace MyNs
{
class MyException1 : Exception
{
}
class MyException2 : Exception
{
}
class TestClass
{
/// <exception cref=""MyException1""></exception>
/// <exception cref=""T:MyNs.MyException2""></exception>
/// <exception cref=""System.Int32""></exception>
/// <exception cref=""double""></exception>
/// <exception cref=""Not_A_Class_But_Still_Displayed""></exception>
void M()
{
M$$();
}
}
}",
Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$();
void local() { i++; this.M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$(i);
void local(int j) { j++; M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction3()
{
await TestAsync(@"
class C
{
public void M(int @this)
{
int i = 0;
local$$();
void local()
{
M(1);
i++;
@this++;
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction4()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction$$()
{
int local = 0;
int InnerLocalFunction()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction()
{
int local = 0;
int InnerLocalFunction$$()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction$$()
{
_ = local1;
void InnerLocalFunction()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction()
{
_ = local1;
void InnerLocalFunction$$()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action a = () =$$> { i++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action<int> a = j =$$> { i++; j++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2_DifferentOrder()
{
await TestAsync(@"
class C
{
void M(int j)
{
int i;
System.Action a = () =$$> { M(); i++; j++; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda3()
{
await TestAsync(@"
class C
{
void M()
{
int i;
int @this;
N(() =$$> { M(); @this++; }, () => { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda4()
{
await TestAsync(@"
class C
{
void M()
{
int i;
N(() => { M(); }, () =$$> { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =$$>
{
int local = 0;
System.Func<int> b = () =>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =>
{
int local = 0;
System.Func<int> b = () =$$>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =$$>
{
_ = local1;
System.Action b = () =>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda8()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =>
{
_ = local1;
System.Action b = () =$$>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnDelegate()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")]
public async Task QuickInfoWithNonStandardSeeAttributesAppear()
{
await TestAsync(
@"class C
{
/// <summary>
/// <see cref=""System.String"" />
/// <see href=""http://microsoft.com"" />
/// <see langword=""null"" />
/// <see unsupported-attribute=""cat"" />
/// </summary>
void M()
{
M$$();
}
}",
Documentation(@"string http://microsoft.com null cat"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")]
public async Task OptionalParameterFromPreviousSubmission()
{
const string workspaceDefinition = @"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
void M(int x = 1) { }
</Submission>
<Submission Language=""C#"" CommonReferences=""true"">
M(x$$: 2)
</Submission>
</Workspace>
";
using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive);
await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TupleProperty()
{
await TestInMethodAsync(
@"interface I
{
(int, int) Name { get; set; }
}
class C : I
{
(int, int) I.Name$$
{
get
{
throw new System.Exception();
}
set
{
}
}
}",
MainDescription("(int, int) C.Name { get; set; }"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create();
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create();
}
}
",
MainDescription("struct System.ValueTuple"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1);
}
}
",
MainDescription("struct System.ValueTuple<System.Int32>"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1, 1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) (int, int) y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1, 1);
}
}
",
MainDescription("(System.Int32, System.Int32)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefMethod()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int i = ref $$goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription("ref int Program.goo()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLocal()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int $$i = ref goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription($"({FeaturesResources.local_variable}) ref int i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")]
public async Task TestGenericMethodInDocComment()
{
await TestAsync(
@"
class Test
{
T F<T>()
{
F<T>();
}
/// <summary>
/// <see cref=""F$${T}()""/>
/// </summary>
void S()
{ }
}
",
MainDescription("T Test.F<T>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")]
public async Task TestExceptionWithCrefToConstructorDoesNotCrash()
{
await TestAsync(
@"
class Test
{
/// <summary>
/// </summary>
/// <exception cref=""Test.Test""/>
public Test$$() {}
}
",
MainDescription("Test.Test()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct()
{
var markup = "ref struct X$$ {}";
await TestAsync(markup, MainDescription("ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct_Nested()
{
var markup = @"
namespace Nested
{
ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("ref struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct()
{
var markup = "readonly struct X$$ {}";
await TestAsync(markup, MainDescription("readonly struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct()
{
var markup = "readonly ref struct X$$ {}";
await TestAsync(markup, MainDescription("readonly ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly ref struct Nested.X"));
}
[WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLikeTypesNoDeprecated()
{
var xmlString = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
public ref struct TestRef
{
}
</Document>
</MetadataReferenceFromSource>
<Document FilePath=""SourceDocument"">
ref struct Test
{
private $$TestRef _field;
}
</Document>
</Project>
</Workspace>";
// There should be no [deprecated] attribute displayed.
await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType()
{
await TestAsync(
@"namespace ConsoleApplication1
{
class Program
{
static A B { get; set; }
static B A { get; set; }
static void Main(string[] args)
{
B = ConsoleApplication1.B$$.F();
}
}
class A { }
class B
{
public static A F() => null;
}
}",
MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType2()
{
await TestAsync(
@"using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
public static List<Bar> Bar { get; set; }
static void Main(string[] args)
{
Tes$$t<Bar>();
}
static void Test<T>() { }
}
class Bar
{
}
}",
MainDescription($"void Program.Test<Bar>()"));
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_01()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b.Content$$Type, out var chars)
{
}
}
}
");
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_02()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b$$.ContentType, out var chars)
{
}
}
}
",
MainDescription($"({ FeaturesResources.parameter }) ? b"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Enum
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Delegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task MulticastDelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.MulticastDelegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : unmanaged
{
}",
MainDescription("class X<T> where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : unmanaged { }
}",
MainDescription("void X.M<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : unmanaged;",
MainDescription("delegate void D<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : unmanaged { }
}
}",
MainDescription("void M<T>() where T : unmanaged"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { g$$et; set; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { get; s$$et; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
a$$dd => throw null;
remove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo +$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
add => throw null;
r$$emove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo -$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task BuiltInOperatorWithUserDefinedEquivalent()
{
await TestAsync(
@"
class X
{
void N(string a, string b)
{
var v = a $$== b;
}
}",
MainDescription("bool string.operator ==(string a, string b)"),
SymbolGlyph(Glyph.Operator));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : notnull
{
}",
MainDescription("class X<T> where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : notnull { }
}",
MainDescription("void X.M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : notnull;",
MainDescription("delegate void D<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : notnull { }
}
}",
MainDescription("void M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
S = """";
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string?> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = null;
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownPriorToLanguageVersion8()
{
await TestWithOptionsAsync(TestOptions.Regular7_3,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownInNullableDisable()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable disable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableShownWhenEnabledGlobally()
{
await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable),
@"using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForValueType()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
int a = 0;
int b = $$a;
}
}",
MainDescription($"({FeaturesResources.local_variable}) int a"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForConst()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
const string? s = null;
string? s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_constant}) string? s = null"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocInlineSummary()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels1()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <inheritdoc cref=""M()""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels2()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <summary><inheritdoc cref=""M()""/></summary>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocWithTypeParamRef()
{
var markup =
@"
public class Program
{
public static void Main() => _ = new Test<int>().$$Clone();
}
public class Test<T> : ICloneable<Test<T>>
{
/// <inheritdoc/>
public Test<T> Clone() => new();
}
/// <summary>A type that has clonable instances.</summary>
/// <typeparam name=""T"">The type of instances that can be cloned.</typeparam>
public interface ICloneable<T>
{
/// <summary>Clones a <typeparamref name=""T""/>.</summary>
/// <returns>A clone of the <typeparamref name=""T""/>.</returns>
public T Clone();
}";
await TestInClassAsync(markup,
MainDescription("Test<int> Test<int>.Clone()"),
Documentation("Clones a Test<T>."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle1()
{
var markup =
@"
/// <inheritdoc cref=""M(int, int)""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle2()
{
var markup =
@"
/// <inheritdoc cref=""M(int)""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle3()
{
var markup =
@"
/// <inheritdoc cref=""M""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")]
public async Task TestLinqGroupVariableDeclaration()
{
var code =
@"
void M(string[] a)
{
var v = from x in a
group x by x.Length into $$g
select g;
}";
await TestInClassAsync(code,
MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerCloseBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()[5$$];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerOpenBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()$$[5];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexer_NotOnArrayAccess()
{
await TestAsync(@"
class Program
{
void M()
{
int[] x = new int[4];
int y = x[3$$];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is not $$Person p)
{
}
}
}",
MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$not Person p)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$Person or int)
{
}
}
}", MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person or $$int)
{
}
}
}", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern3()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person $$or int)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoDerivedRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
}
record Student(string Id)
{
void M($$Student p)
{
}
}
", MainDescription("record Student"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")]
public async Task QuickInfoRecord_BaseTypeList()
{
await TestAsync(@"
record Person(string First, string Last);
record Student(int Id) : $$Person(null, null);
", MainDescription("Person.Person(string First, string Last)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfo_BaseConstructorInitializer()
{
await TestAsync(@"
public class Person { public Person(int id) { } }
public class Student : Person { public Student() : $$base(0) { } }
", MainDescription("Person.Person(int id)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordClass()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record class Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoReadOnlyRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"readonly record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("readonly record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")]
public async Task TestVarPatternOnVarKeyword()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is va$$r x && x.Length > 0)
{
}
}
}",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVarPatternOnVariableItself()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is var x$$ && x.Length > 0)
{
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? x"));
}
[WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationCData()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// summary for interface IGoo
/// <code><![CDATA[
/// List<string> y = null;
/// ]]></code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"summary for interface IGoo
List<string> y = null;"));
}
[WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DoNotNormalizeWhitespaceForCode()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// Normalize this, and <c>Also this</c>
/// <code>
/// line 1
/// line 2
/// </code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"Normalize this, and Also this
line 1
line 2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation_FromReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void M1() { }
}
class R
{
public static void M() { C1_1.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_FromTypeParameterReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class R
{
public static void M<T>() where T : I1 { T.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void I1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_01()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class Program
{
System.Delegate D = bo$$ol () => true;
}",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_02()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A
{
struct B { }
System.Delegate D = A.B$$ () => null;
}",
MainDescription("struct A.B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_03()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A<T>
{
}
struct B
{
System.Delegate D = A<B$$> () => null;
}",
MainDescription("struct B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNormalFuncSynthesizedLambdaType()
{
await TestAsync(
@"class C
{
void M()
{
$$var v = (int i) => i.ToString();
}
}",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap($@"
T {FeaturesResources.is_} int
TResult {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousSynthesizedLambdaType()
{
await TestAsync(
@"class C
{
void M()
{
$$var v = (ref int i) => i.ToString();
}
}",
MainDescription("delegate string <anonymous delegate>(ref int)"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Security;
using System.Threading;
using System.Threading.Tasks;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Editor.UnitTests.QuickInfo;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.QuickInfo;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
using static Microsoft.CodeAnalysis.Editor.UnitTests.Classification.FormattedClassifications;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.QuickInfo
{
public class SemanticQuickInfoSourceTests : AbstractSemanticQuickInfoSourceTests
{
private static async Task TestWithOptionsAsync(CSharpParseOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(CSharpCompilationOptions options, string markup, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.CreateCSharp(markup, compilationOptions: options);
await TestWithOptionsAsync(workspace, expectedResults);
}
private static async Task TestWithOptionsAsync(TestWorkspace workspace, params Action<QuickInfoItem>[] expectedResults)
{
var testDocument = workspace.DocumentWithCursor;
var position = testDocument.CursorPosition.GetValueOrDefault();
var documentId = workspace.GetDocumentId(testDocument);
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
await TestWithOptionsAsync(document, service, position, expectedResults);
// speculative semantic model
if (await CanUseSpeculativeSemanticModelAsync(document, position))
{
var buffer = testDocument.GetTextBuffer();
using (var edit = buffer.CreateEdit())
{
var currentSnapshot = buffer.CurrentSnapshot;
edit.Replace(0, currentSnapshot.Length, currentSnapshot.GetText());
edit.Apply();
}
await TestWithOptionsAsync(document, service, position, expectedResults);
}
}
private static async Task TestWithOptionsAsync(Document document, QuickInfoService service, int position, Action<QuickInfoItem>[] expectedResults)
{
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
private static async Task VerifyWithMscorlib45Async(string markup, Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""C#"" CommonReferencesNet45=""true"">
<Document FilePath=""SourceDocument"">
{0}
</Document>
</Project>
</Workspace>", SecurityElement.Escape(markup));
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.Single(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.Where(d => d.Name == "SourceDocument").Single().Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected override async Task TestAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
await TestWithOptionsAsync(Options.Regular, markup, expectedResults);
await TestWithOptionsAsync(Options.Script, markup, expectedResults);
}
private async Task TestWithUsingsAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupWithUsings =
@"using System;
using System.Collections.Generic;
using System.Linq;
" + markup;
await TestAsync(markupWithUsings, expectedResults);
}
private Task TestInClassAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInClass = "class C { " + markup + " }";
return TestWithUsingsAsync(markupInClass, expectedResults);
}
private Task TestInMethodAsync(string markup, params Action<QuickInfoItem>[] expectedResults)
{
var markupInMethod = "class C { void M() { " + markup + " } }";
return TestWithUsingsAsync(markupInMethod, expectedResults);
}
private static async Task TestWithReferenceAsync(string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
await TestWithMetadataReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
await TestWithProjectReferenceHelperAsync(sourceCode, referencedCode, sourceLanguage, referencedLanguage, expectedResults);
// Multi-language projects are not supported.
if (sourceLanguage == referencedLanguage)
{
await TestInSameProjectHelperAsync(sourceCode, referencedCode, sourceLanguage, expectedResults);
}
}
private static async Task TestWithMetadataReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<MetadataReferenceFromSource Language=""{2}"" CommonReferences=""true"" IncludeXmlDocComments=""true"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</MetadataReferenceFromSource>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestWithProjectReferenceHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
string referencedLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<ProjectReference>ReferencedProject</ProjectReference>
<Document FilePath=""SourceDocument"">
{1}
</Document>
</Project>
<Project Language=""{2}"" CommonReferences=""true"" AssemblyName=""ReferencedProject"">
<Document FilePath=""ReferencedDocument"">
{3}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode),
referencedLanguage, SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task TestInSameProjectHelperAsync(
string sourceCode,
string referencedCode,
string sourceLanguage,
params Action<QuickInfoItem>[] expectedResults)
{
var xmlString = string.Format(@"
<Workspace>
<Project Language=""{0}"" CommonReferences=""true"">
<Document FilePath=""SourceDocument"">
{1}
</Document>
<Document FilePath=""ReferencedDocument"">
{2}
</Document>
</Project>
</Workspace>", sourceLanguage, SecurityElement.Escape(sourceCode), SecurityElement.Escape(referencedCode));
await VerifyWithReferenceWorkerAsync(xmlString, expectedResults);
}
private static async Task VerifyWithReferenceWorkerAsync(string xmlString, params Action<QuickInfoItem>[] expectedResults)
{
using var workspace = TestWorkspace.Create(xmlString);
var position = workspace.Documents.First(d => d.Name == "SourceDocument").CursorPosition.Value;
var documentId = workspace.Documents.First(d => d.Name == "SourceDocument").Id;
var document = workspace.CurrentSolution.GetDocument(documentId);
var service = QuickInfoService.GetService(document);
var info = await service.GetQuickInfoAsync(document, position, cancellationToken: CancellationToken.None);
if (expectedResults.Length == 0)
{
Assert.Null(info);
}
else
{
Assert.NotNull(info);
foreach (var expected in expectedResults)
{
expected(info);
}
}
}
protected async Task TestInvalidTypeInClassAsync(string code)
{
var codeInClass = "class C { " + code + " }";
await TestAsync(codeInClass);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective()
{
await TestAsync(
@"using $$System;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective2()
{
await TestAsync(
@"using System.Coll$$ections.Generic;",
MainDescription("namespace System.Collections"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirective3()
{
await TestAsync(
@"using System.L$$inq;",
MainDescription("namespace System.Linq"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNamespaceInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = Sys$$tem.Console;",
MainDescription("namespace System"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeInUsingDirectiveWithAlias()
{
await TestAsync(
@"using Goo = System.Con$$sole;",
MainDescription("class System.Console"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias()
{
var markup =
@"using I$$ = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias2()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo { }
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[WorkItem(991466, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/991466")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationInUsingDirectiveWithAlias3()
{
var markup =
@"using I = IGoo;
///<summary>summary for interface IGoo</summary>
interface IGoo
{
void Goo();
}
class C : I$$ { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation("summary for interface IGoo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestThis()
{
var markup =
@"
///<summary>summary for Class C</summary>
class C { string M() { return thi$$s.ToString(); } }";
await TestWithUsingsAsync(markup,
MainDescription("class C"),
Documentation("summary for Class C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestClassWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
class C { void M() { $$C obj; } }";
await TestAsync(markup,
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingleLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedSingleLineComment
// SingleLine doc comment with leading whitespace
await TestAsync(
@"///<summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/// <summary>Hello!</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with leading whitespace and blank line
await TestAsync(
@"///<summary>Hello!
///</summary>
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// SingleLine doc comment with '\r' line separators
await TestAsync("///<summary>Hello!\r///</summary>\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultiLineDocComments()
{
// Tests chosen to maximize code coverage in DocumentationCommentCompiler.WriteFormattedMultiLineComment
// Multiline doc comment with leading whitespace
await TestAsync(
@"/**<summary>Hello!</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag
await TestAsync(
@"/** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with space before opening tag and leading whitespace
await TestAsync(
@"/**
** <summary>Hello!</summary>
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with no per-line prefix
await TestAsync(
@"/**
<summary>
Hello!
</summary>
*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with inconsistent per-line prefix
await TestAsync(
@"/**
** <summary>
Hello!</summary>
**
**/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with closing comment on final line
await TestAsync(
@"/**
<summary>Hello!
</summary>*/
class C
{
void M()
{
$$C obj;
}
}",
MainDescription("class C"),
Documentation("Hello!"));
// Multiline doc comment with '\r' line separators
await TestAsync("/**\r* <summary>\r* Hello!\r* </summary>\r*/\rclass C { void M() { $$C obj; } }",
MainDescription("class C"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
void M() { M$$() }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello!"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInt32()
{
await TestInClassAsync(
@"$$Int32 i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInInt()
{
await TestInClassAsync(
@"$$int i;",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestString()
{
await TestInClassAsync(
@"$$String s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInString()
{
await TestInClassAsync(
@"$$string s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInStringAtEndOfToken()
{
await TestInClassAsync(
@"string$$ s;",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBoolean()
{
await TestInClassAsync(
@"$$Boolean b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInBool()
{
await TestInClassAsync(
@"$$bool b;",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSingle()
{
await TestInClassAsync(
@"$$Single s;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestBuiltInFloat()
{
await TestInClassAsync(
@"$$float f;",
MainDescription("struct System.Single"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVoidIsInvalid()
{
await TestInvalidTypeInClassAsync(
@"$$void M()
{
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer1_931958()
{
await TestInvalidTypeInClassAsync(
@"$$T* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer2_931958()
{
await TestInvalidTypeInClassAsync(
@"T$$* i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidPointer3_931958()
{
await TestInvalidTypeInClassAsync(
@"T*$$ i;");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfString()
{
await TestInClassAsync(
@"$$List<string> l;",
MainDescription("class System.Collections.Generic.List<T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfSomethingFromSource()
{
var markup =
@"
///<summary>Generic List</summary>
public class GenericList<T> { Generic$$List<int> t; }";
await TestAsync(markup,
MainDescription("class GenericList<T>"),
Documentation("Generic List"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestListOfT()
{
await TestInMethodAsync(
@"class C<T>
{
$$List<T> l;
}",
MainDescription("class System.Collections.Generic.List<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfIntAndString()
{
await TestInClassAsync(
@"$$Dictionary<int, string> d;",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} int",
$"TValue {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDictionaryOfTAndU()
{
await TestInMethodAsync(
@"class C<T, U>
{
$$Dictionary<T, U> d;
}",
MainDescription("class System.Collections.Generic.Dictionary<TKey, TValue>"),
TypeParameterMap(
Lines($"\r\nTKey {FeaturesResources.is_} T",
$"TValue {FeaturesResources.is_} U")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIEnumerableOfInt()
{
await TestInClassAsync(
@"$$IEnumerable<int> M()
{
yield break;
}",
MainDescription("interface System.Collections.Generic.IEnumerable<out T>"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventHandler()
{
await TestInClassAsync(
@"event $$EventHandler e;",
MainDescription("delegate void System.EventHandler(object sender, System.EventArgs e)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter()
{
await TestAsync(
@"class C<T>
{
$$T t;
}",
MainDescription($"T {FeaturesResources.in_} C<T>"));
}
[WorkItem(538636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538636")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterWithDocComment()
{
var markup =
@"
///<summary>Hello!</summary>
///<typeparam name=""T"">T is Type Parameter</typeparam>
class C<T> { $$T t; }";
await TestAsync(markup,
MainDescription($"T {FeaturesResources.in_} C<T>"),
Documentation("T is Type Parameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter1_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
$$T11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter2_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T$$11 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter3_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T1$$1 t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameter4_Bug931949()
{
await TestAsync(
@"class T1<T11>
{
T11$$ t;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableOfInt()
{
await TestInClassAsync(@"$$Nullable<int> i; }",
MainDescription("struct System.Nullable<T> where T : struct"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod1_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>($$T1 i) where T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod2_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where $$T1 : struct
{
T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeDeclaredOnMethod3_Bug1946()
{
await TestAsync(
@"class C
{
static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Class()
{
await TestAsync(
@"class C<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} C<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Struct()
{
await TestAsync(
@"struct S<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} S<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Interface()
{
await TestAsync(
@"interface I<T> where $$T : class
{
}",
MainDescription($"T {FeaturesResources.in_} I<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericTypeParameterConstraint_Delegate()
{
await TestAsync(
@"delegate void D<T>() where $$T : class;",
MainDescription($"T {FeaturesResources.in_} D<T> where T : class"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMinimallyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FullyQualifiedConstraint()
{
await TestAsync(@"class C<T> where $$T : System.Collections.Generic.IEnumerable<int>",
MainDescription($"T {FeaturesResources.in_} C<T> where T : System.Collections.Generic.IEnumerable<int>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethod()
{
await TestAsync(
@"class C
{
void M()
{
M$$();
}
}",
MainDescription("void C.M()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMethodReferenceInSameMethodWithDocComment()
{
var markup =
@"
///<summary>Hello World</summary>
void M() { M$$(); }";
await TestInClassAsync(markup,
MainDescription("void C.M()"),
Documentation("Hello World"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn()
{
var markup =
@"int field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltIn2()
{
await TestInClassAsync(
@"int field;
void M()
{
int f = field$$;
}",
MainDescription($"({FeaturesResources.field}) int C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodBuiltInWithFieldInitializer()
{
await TestInClassAsync(
@"int field = 1;
void M()
{
int f = field $$;
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn()
{
await TestInMethodAsync(
@"int x;
x = x$$+1;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn1()
{
await TestInMethodAsync(
@"int x;
x = x$$ + 1;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn2()
{
await TestInMethodAsync(
@"int x;
x = x+$$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn3()
{
await TestInMethodAsync(
@"int x;
x = x +$$ x;",
MainDescription("int int.operator +(int left, int right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorBuiltIn4()
{
await TestInMethodAsync(
@"int x;
x = x + $$x;",
MainDescription($"({FeaturesResources.local_variable}) int x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeBuiltIn()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
}";
await TestAsync(markup);
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOperatorCustomTypeOverload()
{
var markup =
@"class C
{
static void M() { C c; c = c +$$ c; }
static C operator+(C a, C b) { return a; }
}";
await TestAsync(markup,
MainDescription("C C.operator +(C a, C b)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodMinimal()
{
var markup =
@"DateTime field;
void M()
{
field$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldInMethodQualified()
{
var markup =
@"System.IO.FileInfo file;
void M()
{
file$$
}";
await TestInClassAsync(markup,
MainDescription($"({FeaturesResources.field}) System.IO.FileInfo C.file"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { int a = MyStruct.Some$$Field; }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSource()
{
var markup =
@"struct MyStruct {
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"));
}
[WorkItem(538638, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538638")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMemberOfStructInsideMethodFromSourceWithDocComment()
{
var markup =
@"struct MyStruct {
///<summary>My Field</summary>
public static int SomeField; }
static class Test { static void Method() { int a = MyStruct.Some$$Field; } }";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static int MyStruct.SomeField"),
Documentation("My Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldMinimal()
{
await TestInMethodAsync(@"DateTime dt = DateTime.MaxValue$$",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified1()
{
// NOTE: we qualify the field type, but not the type that contains the field in Dev10
var markup =
@"class C {
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}";
await TestAsync(markup,
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified2()
{
await TestAsync(
@"class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly System.DateTime System.DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMetadataFieldQualified3()
{
await TestAsync(
@"using System;
class C
{
void M()
{
DateTime dt = System.DateTime.MaxValue$$
}
}",
MainDescription($"({FeaturesResources.field}) static readonly DateTime DateTime.MaxValue"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
}
class D
{
void M()
{
new C<int>().Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) int C<int>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericField()
{
await TestAsync(
@"class C<T>
{
public T Field;
void M()
{
Fi$$eld.ToString();
}
}",
MainDescription($"({FeaturesResources.field}) T C<T>.Field"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIntegerLiteral()
{
await TestInMethodAsync(@"int f = 37$$",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrueKeyword()
{
await TestInMethodAsync(@"bool f = true$$",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFalseKeyword()
{
await TestInMethodAsync(@"bool f = false$$",
MainDescription("struct System.Boolean"));
}
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteral()
{
await TestInMethodAsync(@"string f = null$$",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullLiteralWithVar()
=> await TestInMethodAsync(@"var f = null$$");
[WorkItem(26027, "https://github.com/dotnet/roslyn/issues/26027")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDefaultLiteral()
{
await TestInMethodAsync(@"string f = default$$",
MainDescription("class System.String"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnGenericTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
aw$$ait Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordInDeclarationStatement()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async Task<int> Calc()
{
var x = $$await Calc();
return 5;
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitKeywordOnTaskReturningAsync()
{
var markup = @"using System.Threading.Tasks;
class C
{
public async void Calc()
{
aw$$ait Task.Delay(100);
}
}";
await TestAsync(markup, MainDescription(FeaturesResources.Awaited_task_returns_no_value));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords1()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = await awa$$it resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, $"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>")),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAwaitKeywords2()
{
var markup = @"using System;
using System.Threading.Tasks;
class AsyncExample2
{
async Task<Task<int>> AsyncMethod()
{
return NewMethod();
}
private static Task<int> NewMethod()
{
int hours = 24;
return hours;
}
async Task UseAsync()
{
Func<Task<int>> lambda = async () =>
{
return await await AsyncMethod();
};
int result = await await AsyncMethod();
Task<Task<int>> resultTask = AsyncMethod();
result = awa$$it await resultTask;
result = await lambda();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "struct System.Int32")));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitablePrefixOnCustomAwaiter()
{
var markup = @"using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Z = $$C;
class C
{
public MyAwaiter GetAwaiter() { throw new NotImplementedException(); }
}
class MyAwaiter : INotifyCompletion
{
public void OnCompleted(Action continuation)
{
throw new NotImplementedException();
}
public bool IsCompleted { get { throw new NotImplementedException(); } }
public void GetResult() { }
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class C"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskType()
{
var markup = @"using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$ v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task"));
}
[WorkItem(756226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756226"), WorkItem(756337, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/756337")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTaskOfTType()
{
var markup = @"using System;
using System.Threading.Tasks;
class C
{
public void Calc()
{
Task$$<int> v1;
}
}";
await TestAsync(markup, MainDescription($"({CSharpFeaturesResources.awaitable}) class System.Threading.Tasks.Task<TResult>"),
TypeParameterMap($"\r\nTResult {FeaturesResources.is_} int"));
}
[WorkItem(7100, "https://github.com/dotnet/roslyn/issues/7100")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDynamicIsntAwaitable()
{
var markup = @"
class C
{
dynamic D() { return null; }
void M()
{
D$$();
}
}
";
await TestAsync(markup, MainDescription("dynamic C.D()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStringLiteral()
{
await TestInMethodAsync(@"string f = ""Goo""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimStringLiteral()
{
await TestInMethodAsync(@"string f = @""cat""$$",
MainDescription("class System.String"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[WorkItem(1280, "https://github.com/dotnet/roslyn/issues/1280")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVerbatimInterpolatedStringLiteral()
{
await TestInMethodAsync(@"string f = $@""cat""$$", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""c$$at""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""$$cat""", MainDescription("class System.String"));
await TestInMethodAsync(@"string f = $@""cat {1$$ + 2} dog""", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCharLiteral()
{
await TestInMethodAsync(@"string f = 'x'$$",
MainDescription("struct System.Char"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicKeyword()
{
await TestInMethodAsync(
@"dyn$$amic dyn;",
MainDescription("dynamic"),
Documentation(FeaturesResources.Represents_an_object_whose_operations_will_be_resolved_at_runtime));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicField()
{
await TestInClassAsync(
@"dynamic dyn;
void M()
{
d$$yn.Goo();
}",
MainDescription($"({FeaturesResources.field}) dynamic C.dyn"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal()
{
await TestInClassAsync(
@"DateTime Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet()
{
await TestInClassAsync(
@"public DateTime Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("DateTime C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Minimal_PrivateSet1()
{
await TestInClassAsync(
@"protected internal int Prop { get; private set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("int C.Prop { get; private set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalProperty_Qualified()
{
await TestInClassAsync(
@"System.IO.FileInfo Prop { get; set; }
void M()
{
P$$rop.ToString();
}",
MainDescription("System.IO.FileInfo C.Prop { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Minimal()
{
await TestInMethodAsync(@"DateTime.No$$w.ToString();",
MainDescription("DateTime DateTime.Now { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NonLocalProperty_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo f;
f.Att$$ributes.ToString();",
MainDescription("System.IO.FileAttributes System.IO.FileSystemInfo.Attributes { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ConstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set }
}
class D
{
void M()
{
new C<int>().Pro$$perty.ToString();
}
}",
MainDescription("int C<int>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnconstructedGenericProperty()
{
await TestAsync(
@"class C<T>
{
public T Property { get; set}
void M()
{
Pro$$perty.ToString();
}
}",
MainDescription("T C<T>.Property { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueInProperty()
{
await TestInClassAsync(
@"public DateTime Property
{
set
{
goo = val$$ue;
}
}",
MainDescription($"({FeaturesResources.parameter}) DateTime value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumTypeName()
{
await TestInMethodAsync(@"Consol$$eColor c",
MainDescription("enum System.ConsoleColor"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_Definition()
{
await TestInClassAsync(@"enum E$$ : byte { A, B }",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsField()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ _E;
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsProperty()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ E{ get; set; };
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsParameter()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M(E$$ e) { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsReturnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private E$$ M() { }
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_AsLocal()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
E$$ e = default;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_OnMemberAccessOnType()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E$$.A;
}
",
MainDescription("enum C.E : byte"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
public async Task EnumNonDefaultUnderlyingType_NotOnMemberAccessOnMember()
{
await TestInClassAsync(@"
enum E : byte { A, B }
private void M()
{
var ea = E.A$$;
}
",
MainDescription("E.A = 0"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("byte", "byte")]
[InlineData("byte", "System.Byte")]
[InlineData("sbyte", "sbyte")]
[InlineData("sbyte", "System.SByte")]
[InlineData("short", "short")]
[InlineData("short", "System.Int16")]
[InlineData("ushort", "ushort")]
[InlineData("ushort", "System.UInt16")]
// int is the default type and is not shown
[InlineData("uint", "uint")]
[InlineData("uint", "System.UInt32")]
[InlineData("long", "long")]
[InlineData("long", "System.Int64")]
[InlineData("ulong", "ulong")]
[InlineData("ulong", "System.UInt64")]
public async Task EnumNonDefaultUnderlyingType_ShowForNonDefaultTypes(string displayTypeName, string underlyingTypeName)
{
await TestInClassAsync(@$"
enum E$$ : {underlyingTypeName}
{{
A, B
}}",
MainDescription($"enum C.E : {displayTypeName}"));
}
[Theory, WorkItem(52490, "https://github.com/dotnet/roslyn/issues/52490")]
[InlineData("")]
[InlineData(": int")]
[InlineData(": System.Int32")]
public async Task EnumNonDefaultUnderlyingType_DontShowForDefaultType(string defaultType)
{
await TestInClassAsync(@$"
enum E$$ {defaultType}
{{
A, B
}}",
MainDescription("enum C.E"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromMetadata()
{
await TestInMethodAsync(@"ConsoleColor c = ConsoleColor.Bla$$ck",
MainDescription("ConsoleColor.Black = 0"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata1()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.Cl$$ass",
MainDescription("AttributeTargets.Class = 4"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FlagsEnumMemberNameFromMetadata2()
{
await TestInMethodAsync(@"AttributeTargets a = AttributeTargets.A$$ll",
MainDescription("AttributeTargets.All = AttributeTargets.Assembly | AttributeTargets.Module | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Constructor | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Delegate | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource1()
{
await TestAsync(
@"enum E
{
A = 1 << 0,
B = 1 << 1,
C = 1 << 2
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1 << 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumMemberNameFromSource2()
{
await TestAsync(
@"enum E
{
A,
B,
C
}
class C
{
void M()
{
var e = E.B$$;
}
}",
MainDescription("E.B = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Minimal()
{
await TestInClassAsync(
@"void M(DateTime dt)
{
d$$t.ToString();",
MainDescription($"({FeaturesResources.parameter}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_InMethod_Qualified()
{
await TestInClassAsync(
@"void M(System.IO.FileInfo fileInfo)
{
file$$Info.ToString();",
MainDescription($"({FeaturesResources.parameter}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_FromReferenceToNamedParameter()
{
await TestInMethodAsync(@"Console.WriteLine(va$$lue: ""Hi"");",
MainDescription($"({FeaturesResources.parameter}) string value"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_DefaultValue()
{
// NOTE: Dev10 doesn't show the default value, but it would be nice if we did.
// NOTE: The "DefaultValue" property isn't implemented yet.
await TestInClassAsync(
@"void M(int param = 42)
{
para$$m.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) int param = 42"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Params()
{
await TestInClassAsync(
@"void M(params DateTime[] arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) params DateTime[] arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Ref()
{
await TestInClassAsync(
@"void M(ref DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) ref DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Parameter_Out()
{
await TestInClassAsync(
@"void M(out DateTime arg)
{
ar$$g.ToString();
}",
MainDescription($"({FeaturesResources.parameter}) out DateTime arg"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Minimal()
{
await TestInMethodAsync(
@"DateTime dt;
d$$t.ToString();",
MainDescription($"({FeaturesResources.local_variable}) DateTime dt"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Local_Qualified()
{
await TestInMethodAsync(
@"System.IO.FileInfo fileInfo;
file$$Info.ToString();",
MainDescription($"({FeaturesResources.local_variable}) System.IO.FileInfo fileInfo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MetadataOverload()
{
await TestInMethodAsync("Console.Write$$Line();",
MainDescription($"void Console.WriteLine() (+ 18 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleWithOverload()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod();
}
void Method(int i)
{
}",
MainDescription($"void C.Method() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MoreOverloads()
{
await TestInClassAsync(
@"void Method()
{
Met$$hod(null);
}
void Method(int i)
{
}
void Method(DateTime dt)
{
}
void Method(System.IO.FileInfo fileInfo)
{
}",
MainDescription($"void C.Method(System.IO.FileInfo fileInfo) (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_SimpleInSameClass()
{
await TestInClassAsync(
@"DateTime GetDate(System.IO.FileInfo ft)
{
Get$$Date(null);
}",
MainDescription("DateTime C.GetDate(System.IO.FileInfo ft)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParameter()
{
await TestInClassAsync(
@"void M()
{
Met$$hod();
}
void Method(int i = 0)
{
}",
MainDescription("void C.Method([int i = 0])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalDecimalParameter()
{
await TestInClassAsync(
@"void Goo(decimal x$$yz = 10)
{
}",
MainDescription($"({FeaturesResources.parameter}) decimal xyz = 10"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Generic()
{
// Generic method don't get the instantiation info yet. NOTE: We don't display
// constraint info in Dev10. Should we?
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
Go$$o<int, DateTime>(37);
}",
MainDescription("DateTime C.Goo<int, DateTime>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_UnconstructedGeneric()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg)
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_Inferred()
{
await TestInClassAsync(
@"void Goo<TIn>(TIn arg)
{
Go$$o(42);
}",
MainDescription("void C.Goo<int>(int arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_MultipleParams()
{
await TestInClassAsync(
@"void Goo(DateTime dt, System.IO.FileInfo fi, int number)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(DateTime dt, System.IO.FileInfo fi, int number)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_OptionalParam()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(int num = 42)
{
Go$$o();
}",
MainDescription("void C.Goo([int num = 42])"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Method_ParameterModifiers()
{
// NOTE - Default values aren't actually returned by symbols yet.
await TestInClassAsync(
@"void Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)
{
Go$$o(DateTime.Now, null, 32);
}",
MainDescription("void C.Goo(ref DateTime dt, out System.IO.FileInfo fi, params int[] numbers)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor()
{
await TestInClassAsync(
@"public C()
{
}
void M()
{
new C$$().ToString();
}",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Overloads()
{
await TestInClassAsync(
@"public C()
{
}
public C(DateTime dt)
{
}
public C(int i)
{
}
void M()
{
new C$$(DateTime.MaxValue).ToString();
}",
MainDescription($"C.C(DateTime dt) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromStringLiteral()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException("""");",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_UnknownType()
{
await TestInvalidTypeInClassAsync(
@"void M()
{
new G$$oo();
}");
}
/// <summary>
/// Regression for 3923
/// </summary>
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_OverloadFromProperty()
{
await TestInMethodAsync(
@"new InvalidOperatio$$nException(this.GetType().Name);",
MainDescription($"InvalidOperationException.InvalidOperationException(string message) (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_Metadata()
{
await TestInMethodAsync(
@"new Argument$$NullException();",
MainDescription($"ArgumentNullException.ArgumentNullException() (+ 3 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_MetadataQualified()
{
await TestInMethodAsync(@"new System.IO.File$$Info(null);",
MainDescription("System.IO.FileInfo.FileInfo(string fileName)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InterfaceProperty()
{
await TestInMethodAsync(
@"interface I
{
string Name$$ { get; set; }
}",
MainDescription("string I.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExplicitInterfacePropertyImplementation()
{
await TestInMethodAsync(
@"interface I
{
string Name { get; set; }
}
class C : I
{
string IEmployee.Name$$
{
get
{
return """";
}
set
{
}
}
}",
MainDescription("string C.Name { get; set; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Operator()
{
await TestInClassAsync(
@"public static C operator +(C left, C right)
{
return null;
}
void M(C left, C right)
{
return left +$$ right;
}",
MainDescription("C C.operator +(C left, C right)"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut G$$oo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>
{
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : IEquatable<TIn>"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethodWithMultipleConstraintsAtDeclaration()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee, new()"));
}
#pragma warning disable CA2243 // Attribute string literals should parse correctly
[WorkItem(792629, "generic type parameter constraints for methods in quick info")]
#pragma warning restore CA2243 // Attribute string literals should parse correctly
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnConstructedGenericMethodWithConstraintsAtInvocation()
{
await TestInClassAsync(
@"TOut Goo<TIn, TOut>(TIn arg) where TIn : Employee
{
Go$$o<TIn, TOut>(default(TIn);
}",
MainDescription("TOut C.Goo<TIn, TOut>(TIn arg) where TIn : Employee"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericTypeWithConstraintsAtDeclaration()
{
await TestAsync(
@"public class Employee : IComparable<Employee>
{
public int CompareTo(Employee other)
{
throw new NotImplementedException();
}
}
class Emplo$$yeeList<T> : IEnumerable<T> where T : Employee, System.IComparable<T>, new()
{
}",
MainDescription("class EmployeeList<T> where T : Employee, System.IComparable<T>, new()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericType()
{
await TestAsync(
@"class T1<T11>
{
$$T11 i;
}",
MainDescription($"T11 {FeaturesResources.in_} T1<T11>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericMethod()
{
await TestInClassAsync(
@"static void Meth1<T1>(T1 i) where T1 : struct
{
$$T1 i;
}",
MainDescription($"T1 {FeaturesResources.in_} C.Meth1<T1> where T1 : struct"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Var()
{
await TestInMethodAsync(
@"var x = new Exception();
var y = $$x;",
MainDescription($"({FeaturesResources.local_variable}) Exception x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableReference()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
@"class A<T>
{
}
class B
{
static void M()
{
A<B?>? x = null!;
var y = x;
$$y.ToString();
}
}",
// https://github.com/dotnet/roslyn/issues/26198 public API should show inferred nullability
MainDescription($"({FeaturesResources.local_variable}) A<B?> y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26648, "https://github.com/dotnet/roslyn/issues/26648")]
public async Task NullableReference_InMethod()
{
var code = @"
class G
{
void M()
{
C c;
c.Go$$o();
}
}
public class C
{
public string? Goo(IEnumerable<object?> arg)
{
}
}";
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp8),
code, MainDescription("string? C.Goo(IEnumerable<object?> arg)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedInGeneric()
{
await TestInMethodAsync(
@"List<int>.Enu$$merator e;",
MainDescription("struct System.Collections.Generic.List<T>.Enumerator"),
TypeParameterMap($"\r\nT {FeaturesResources.is_} int"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NestedGenericInGeneric()
{
await TestAsync(
@"class Outer<T>
{
class Inner<U>
{
}
static void M()
{
Outer<int>.I$$nner<string> e;
}
}",
MainDescription("class Outer<T>.Inner<U>"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"U {FeaturesResources.is_} string")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer1()
{
await TestInClassAsync(
@"void M()
{
var x = new test() { $$z = 5 };
}
class test
{
public int z;
}",
MainDescription($"({FeaturesResources.field}) int test.z"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObjectInitializer2()
{
await TestInMethodAsync(
@"class C
{
void M()
{
var x = new test() { z = $$5 };
}
class test
{
public int z;
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(537880, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537880")]
public async Task TypeArgument()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
$$variable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ForEachLoop_1()
{
await TestInMethodAsync(
@"int bb = 555;
bb = bb + 1;
foreach (int cc in new int[]{ 1,2,3}){
c$$c = 1;
bb = bb + 21;
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_1()
{
await TestInMethodAsync(
@"try
{
int aa = 555;
a$$a = aa + 1;
}
catch (Exception ex)
{
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_2()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var y = e$$x;
var z = y;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) Exception ex"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_3()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
var aa = 555;
aa = a$$a + 1;
}
finally
{
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TryCatchFinally_4()
{
await TestInMethodAsync(
@"try
{
}
catch (Exception ex)
{
}
finally
{
int aa = 555;
aa = a$$a + 1;
}",
MainDescription($"({FeaturesResources.local_variable}) int aa"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task GenericVariable()
{
await TestAsync(
@"class C<T, Y>
{
void M()
{
C<int, DateTime> variable;
var$$iable = new C<int, DateTime>();
}
}",
MainDescription($"({FeaturesResources.local_variable}) C<int, DateTime> variable"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInstantiation()
{
await TestAsync(
@"using System.Collections.Generic;
class Program<T>
{
static void Main(string[] args)
{
var p = new Dictio$$nary<int, string>();
}
}",
MainDescription($"Dictionary<int, string>.Dictionary() (+ 5 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUsingAlias_Bug4141()
{
await TestAsync(
@"using X = A.C;
class A
{
public class C
{
}
}
class D : X$$
{
}",
MainDescription(@"class A.C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestFieldOnDeclaration()
{
await TestInClassAsync(
@"DateTime fie$$ld;",
MainDescription($"({FeaturesResources.field}) DateTime C.field"));
}
[WorkItem(538767, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538767")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGenericErrorFieldOnDeclaration()
{
await TestInClassAsync(
@"NonExistentType<int> fi$$eld;",
MainDescription($"({FeaturesResources.field}) NonExistentType<int> C.field"));
}
[WorkItem(538822, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538822")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateType()
{
await TestInClassAsync(
@"Fun$$c<int, string> field;",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap(
Lines($"\r\nT {FeaturesResources.is_} int",
$"TResult {FeaturesResources.is_} string")));
}
[WorkItem(538824, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538824")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnDelegateInvocation()
{
await TestAsync(
@"class Program
{
delegate void D1();
static void Main()
{
D1 d = Main;
$$d();
}
}",
MainDescription($"({FeaturesResources.local_variable}) D1 d"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation1()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = n$$ew int[0];
}
}", MainDescription("int[]"));
}
[WorkItem(539240, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539240")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestOnArrayCreation2()
{
await TestAsync(
@"class Program
{
static void Main()
{
int[] a = new i$$nt[0];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation()
{
await TestAsync(
@"class C
{
static void Main()
{
C c = ne$$w();
}
}
",
MainDescription("C.C()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Constructor_ImplicitObjectCreation_WithParameters()
{
await TestAsync(
@"class C
{
C(int i) { }
C(string s) { }
static void Main()
{
C c = ne$$w(1);
}
}
",
MainDescription($"C.C(int i) (+ 1 {FeaturesResources.overload})"));
}
[WorkItem(539841, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539841")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIsNamedTypeAccessibleForErrorTypes()
{
await TestAsync(
@"sealed class B<T1, T2> : A<B<T1, T2>>
{
protected sealed override B<A<T>, A$$<T>> N()
{
}
}
internal class A<T>
{
}",
MainDescription("class A<T>"));
}
[WorkItem(540075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540075")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType()
{
await TestAsync(
@"using Goo = Goo;
class C
{
void Main()
{
$$Goo
}
}",
MainDescription("Goo"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
$$_ = M();
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnderscoreLocalInAssignment()
{
await TestAsync(
@"class C
{
int M()
{
var $$_ = M();
}
}",
MainDescription($"({FeaturesResources.local_variable}) int _"));
}
[WorkItem(16662, "https://github.com/dotnet/roslyn/issues/16662")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestShortDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out $$_);
i = 0;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInOutVar()
{
await TestAsync(
@"class C
{
void M(out int i)
{
M(out var $$_);
i = 0;
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInIsPattern()
{
await TestAsync(
@"class C
{
void M()
{
if (3 is int $$_) { }
}
}"); // No quick info (see issue #16667)
}
[WorkItem(16667, "https://github.com/dotnet/roslyn/issues/16667")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDiscardInSwitchPattern()
{
await TestAsync(
@"class C
{
void M()
{
switch (3)
{
case int $$_:
return;
}
}
}"); // No quick info (see issue #16667)
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_FirstDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = ($$_, _) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) string _"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLambdaDiscardParameter_SecondDiscard()
{
await TestAsync(
@"class C
{
void M()
{
System.Func<string, int, int> f = (_, $$_) => 1;
}
}",
MainDescription($"({FeaturesResources.discard}) int _"));
}
[WorkItem(540871, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540871")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLiterals()
{
await TestAsync(
@"class MyClass
{
MyClass() : this($$10)
{
intI = 2;
}
public MyClass(int i)
{
}
static int intI = 1;
public static int Main()
{
return 1;
}
}",
MainDescription("struct System.Int32"));
}
[WorkItem(541444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541444")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorInForeach()
{
await TestAsync(
@"class C
{
void Main()
{
foreach (int cc in null)
{
$$cc = 1;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) int cc"));
}
[WorkItem(541678, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541678")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnEvent()
{
await TestAsync(
@"using System;
public class SampleEventArgs
{
public SampleEventArgs(string s)
{
Text = s;
}
public String Text { get; private set; }
}
public class Publisher
{
public delegate void SampleEventHandler(object sender, SampleEventArgs e);
public event SampleEventHandler SampleEvent;
protected virtual void RaiseSampleEvent()
{
if (Sam$$pleEvent != null)
SampleEvent(this, new SampleEventArgs(""Hello""));
}
}",
MainDescription("SampleEventHandler Publisher.SampleEvent"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEvent()
{
await TestInMethodAsync(@"System.Console.CancelKeyPres$$s += null;",
MainDescription("ConsoleCancelEventHandler Console.CancelKeyPress"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventPlusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress +$$= null;",
MainDescription("void Console.CancelKeyPress.add"));
}
[WorkItem(542157, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542157")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventMinusEqualsOperator()
{
await TestInMethodAsync(@"System.Console.CancelKeyPress -$$= null;",
MainDescription("void Console.CancelKeyPress.remove"));
}
[WorkItem(541885, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541885")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethod()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] values = {
1
};
bool isArray = 7.I$$n(values);
}
}
public static class MyExtensions
{
public static bool In<T>(this T o, IEnumerable<T> items)
{
return true;
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) bool int.In<int>(IEnumerable<int> items)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this string ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 2 {FeaturesResources.overloads_})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestQuickInfoOnExtensionMethodOverloads2()
{
await TestWithOptionsAsync(Options.Regular,
@"using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
""1"".Test$$Ext();
}
}
public static class Ex
{
public static void TestExt<T>(this T ex)
{
}
public static void TestExt<T>(this T ex, T arg)
{
}
public static void TestExt(this int ex, int arg)
{
}
}",
MainDescription($"({CSharpFeaturesResources.extension}) void string.TestExt<string>() (+ 1 {FeaturesResources.overload})"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query1()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query2()
{
await TestAsync(
@"using System.Linq;
class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query3()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n in new int[] { 1, 2, 3, 4, 5 }
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query4()
{
await TestAsync(
@"class C
{
void M()
{
var q = from n$$ in new int[] { 1, 2, 3, 4, 5 }
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) ? n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query5()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query6()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) object n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query7()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n in new List<object>()
select $$n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query8()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from int n$$ in new List<object>()
select n;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int n"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query9()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x$$ in new List<List<int>>()
from y in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query10()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in $$x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) List<int> x"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query11()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y$$ in x
select y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Query12()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
class C
{
void M()
{
var q = from x in new List<List<int>>()
from y in x
select $$y;
}
}",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedEnumerable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Select<int, int>(Func<int, int> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedQueryable()
{
await TestInMethodAsync(
@"
var q = from i in new int[0].AsQueryable()
$$select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IQueryable<int> IQueryable<int>.Select<int, int>(System.Linq.Expressions.Expression<Func<int, int>> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMappedCustom()
{
await TestAsync(
@"
using System;
using System.Linq;
namespace N {
public static class LazyExt
{
public static Lazy<U> Select<T, U>(this Lazy<T> source, Func<T, U> selector) => new Lazy<U>(() => selector(source.Value));
}
public class C
{
public void M()
{
var lazy = new Lazy<object>();
var q = from i in lazy
$$select i;
}
}
}
",
MainDescription($"({CSharpFeaturesResources.extension}) Lazy<object> Lazy<object>.Select<object, object>(Func<object, object> selector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectNotMapped()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where true
$$select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoLet()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$let j = true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<'a> IEnumerable<int>.Select<int, 'a>(Func<int, 'a> selector)"),
AnonymousTypes($@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int i, bool j }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoWhere()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$where true
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Where<int>(Func<int, bool> predicate)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOneProperty()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByOnePropertyWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i$$, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithComma2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrdering3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$orderby i ascending, i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i $$ascending, i ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach3()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending ,$$ i ascending
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByTwoPropertiesWithOrderingOnEach4()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
orderby i ascending, i $$ascending
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IOrderedEnumerable<int>.ThenBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoOrderByIncomplete()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
where i > 0
orderby$$
",
MainDescription($"({CSharpFeaturesResources.extension}) IOrderedEnumerable<int> IEnumerable<int>.OrderBy<int, ?>(Func<int, ?> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$from i2 in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
from i2 $$in new int[0]
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, int, int>(Func<int, IEnumerable<int>> collectionSelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupBy2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
group i $$by i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoGroupByInto()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$group i by i into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IGrouping<int, int>> IEnumerable<int>.GroupBy<int, int>(Func<int, int> keySelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 $$in new int[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join i2 in new int[0] on i1 equals i2 into g
select g;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<IEnumerable<int>> IEnumerable<int>.GroupJoin<int, int, int, IEnumerable<int>>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, IEnumerable<int>, IEnumerable<int>> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoJoinInto2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join i2 in new int[0] on i1 equals i2 $$into g
select g;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoFromMissing()
{
await TestInMethodAsync(
@"
var q = $$from i in new int[0]
select i;
");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple1()
{
await TestInMethodAsync(
@"
var q = $$from double i in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSimple2()
{
await TestInMethodAsync(
@"
var q = from double i $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany1()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
$$from double d in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.SelectMany<int, double, int>(Func<int, IEnumerable<double>> collectionSelector, Func<int, double, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableSelectMany2()
{
await TestInMethodAsync(
@"
var q = from i in new int[0]
from double d $$in new int[0]
select i;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<double> System.Collections.IEnumerable.Cast<double>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin1()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
$$join int i2 in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin2()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 $$in new double[0] on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> System.Collections.IEnumerable.Cast<int>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin3()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] $$on i1 equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23394, "https://github.com/dotnet/roslyn/issues/23394")]
public async Task QueryMethodinfoRangeVariableJoin4()
{
await TestInMethodAsync(
@"
var q = from i1 in new int[0]
join int i2 in new double[0] on i1 $$equals i2
select i1;
",
MainDescription($"({CSharpFeaturesResources.extension}) IEnumerable<int> IEnumerable<int>.Join<int, int, int, int>(IEnumerable<int> inner, Func<int, int> outerKeySelector, Func<int, int> innerKeySelector, Func<int, int, int> resultSelector)"));
}
[WorkItem(543205, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543205")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorGlobal()
{
await TestAsync(
@"extern alias global;
class myClass
{
static int Main()
{
$$global::otherClass oc = new global::otherClass();
return 0;
}
}",
MainDescription("<global namespace>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffixAndProduceInvalidIdentifier1()
{
await TestAsync(
@"using System;
class classAttribute : Attribute
{
private classAttribute x$$;
}",
MainDescription($"({FeaturesResources.field}) classAttribute classAttribute.x"));
}
[WorkItem(544026, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544026")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DontRemoveAttributeSuffix2()
{
await TestAsync(
@"using System;
class class1Attribute : Attribute
{
private class1Attribute x$$;
}",
MainDescription($"({FeaturesResources.field}) class1Attribute class1Attribute.x"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeQuickInfoBindsToClassTest()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
[Some$$]
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
}
}",
Documentation("class comment"));
}
[WorkItem(1696, "https://github.com/dotnet/roslyn/issues/1696")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AttributeConstructorQuickInfo()
{
await TestAsync(
@"using System;
/// <summary>
/// class comment
/// </summary>
class SomeAttribute : Attribute
{
/// <summary>
/// ctor comment
/// </summary>
public SomeAttribute()
{
var s = new Some$$Attribute();
}
}",
Documentation("ctor comment"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLabel()
{
await TestInClassAsync(
@"void M()
{
Goo:
int Goo;
goto Goo$$;
}",
MainDescription($"({FeaturesResources.label}) Goo"));
}
[WorkItem(542613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542613")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnboundGeneric()
{
await TestAsync(
@"using System;
using System.Collections.Generic;
class C
{
void M()
{
Type t = typeof(L$$ist<>);
}
}",
MainDescription("class System.Collections.Generic.List<T>"),
NoTypeParameterMap);
}
[WorkItem(543113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543113")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousTypeNew1()
{
await TestAsync(
@"class C
{
void M()
{
var v = $$new { };
}
}",
MainDescription(@"AnonymousType 'a"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ }}"));
}
[WorkItem(543873, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543873")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNestedAnonymousType()
{
// verify nested anonymous types are listed in the same order for different properties
// verify first property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Address",
MainDescription(@"'b 'a.Address { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
// verify second property
await TestInMethodAsync(
@"var x = new[] { new { Name = ""BillG"", Address = new { Street = ""1 Microsoft Way"", Zip = ""98052"" } } };
x[0].$$Name",
MainDescription(@"string 'a.Name { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ string Name, 'b Address }}
'b {FeaturesResources.is_} new {{ string Street, string Zip }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543183, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543183")]
public async Task TestAssignmentOperatorInAnonymousType()
{
await TestAsync(
@"class C
{
void M()
{
var a = new { A $$= 0 };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(10731, "DevDiv_Projects/Roslyn")]
public async Task TestErrorAnonymousTypeDoesntShow()
{
await TestInMethodAsync(
@"var a = new { new { N = 0 }.N, new { } }.$$N;",
MainDescription(@"int 'a.N { get; }"),
NoTypeParameterMap,
AnonymousTypes(
$@"
{FeaturesResources.Anonymous_Types_colon}
'a {FeaturesResources.is_} new {{ int N }}"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(543553, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543553")]
public async Task TestArrayAssignedToVar()
{
await TestAsync(
@"class C
{
static void M(string[] args)
{
v$$ar a = args;
}
}",
MainDescription("string[]"));
}
[WorkItem(529139, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529139")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ColorColorRangeVariable()
{
await TestAsync(
@"using System.Collections.Generic;
using System.Linq;
namespace N1
{
class yield
{
public static IEnumerable<yield> Bar()
{
foreach (yield yield in from yield in new yield[0]
select y$$ield)
{
yield return yield;
}
}
}
}",
MainDescription($"({FeaturesResources.range_variable}) N1.yield yield"));
}
[WorkItem(543550, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543550")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoOnOperator()
{
await TestAsync(
@"using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
var v = new Program() $$+ string.Empty;
}
public static implicit operator Program(string s)
{
return null;
}
public static IEnumerable<Program> operator +(Program p1, Program p2)
{
yield return p1;
yield return p2;
}
}",
MainDescription("IEnumerable<Program> Program.operator +(Program p1, Program p2)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantField()
{
await TestAsync(
@"class C
{
const int $$F = 1;",
MainDescription($"({FeaturesResources.constant}) int C.F = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestMultipleConstantFields()
{
await TestAsync(
@"class C
{
public const double X = 1.0, Y = 2.0, $$Z = 3.5;",
MainDescription($"({FeaturesResources.constant}) double C.Z = 3.5"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantDependencies()
{
await TestAsync(
@"class A
{
public const int $$X = B.Z + 1;
public const int Y = 10;
}
class B
{
public const int Z = A.Y + 1;
}",
MainDescription($"({FeaturesResources.constant}) int A.X = B.Z + 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantCircularDependencies()
{
await TestAsync(
@"class A
{
public const int X = B.Z + 1;
}
class B
{
public const int Z$$ = A.X + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = A.X + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflow()
{
await TestAsync(
@"class B
{
public const int Z$$ = int.MaxValue + 1;
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = int.MaxValue + 1"));
}
[WorkItem(544620, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544620")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantOverflowInUncheckedContext()
{
await TestAsync(
@"class B
{
public const int Z$$ = unchecked(int.MaxValue + 1);
}",
MainDescription($"({FeaturesResources.constant}) int B.Z = unchecked(int.MaxValue + 1)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEnumInConstantField()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const int $$x = (int)Days.Sun;
}
}",
MainDescription($"({FeaturesResources.local_constant}) int x = (int)Days.Sun"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantInDefaultExpression()
{
await TestAsync(
@"public class EnumTest
{
enum Days
{
Sun,
Mon,
Tue,
Wed,
Thu,
Fri,
Sat
};
static void Main()
{
const Days $$x = default(Days);
}
}",
MainDescription($"({FeaturesResources.local_constant}) Days x = default(Days)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantParameter()
{
await TestAsync(
@"class C
{
void Bar(int $$b = 1);
}",
MainDescription($"({FeaturesResources.parameter}) int b = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestConstantLocal()
{
await TestAsync(
@"class C
{
void Bar()
{
const int $$loc = 1;
}",
MainDescription($"({FeaturesResources.local_constant}) int loc = 1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType1()
{
await TestInMethodAsync(
@"var $$v1 = new Goo();",
MainDescription($"({FeaturesResources.local_variable}) Goo v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType2()
{
await TestInMethodAsync(
@"var $$v1 = v1;",
MainDescription($"({FeaturesResources.local_variable}) var v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType3()
{
await TestInMethodAsync(
@"var $$v1 = new Goo<Bar>();",
MainDescription($"({FeaturesResources.local_variable}) Goo<Bar> v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType4()
{
await TestInMethodAsync(
@"var $$v1 = &(x => x);",
MainDescription($"({FeaturesResources.local_variable}) ?* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType5()
{
await TestInMethodAsync("var $$v1 = &v1",
MainDescription($"({FeaturesResources.local_variable}) var* v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType6()
{
await TestInMethodAsync("var $$v1 = new Goo[1]",
MainDescription($"({FeaturesResources.local_variable}) Goo[] v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType7()
{
await TestInClassAsync(
@"class C
{
void Method()
{
}
void Goo()
{
var $$v1 = MethodGroup;
}
}",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(544416, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544416")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestErrorType8()
{
await TestInMethodAsync("var $$v1 = Unknown",
MainDescription($"({FeaturesResources.local_variable}) ? v1"));
}
[WorkItem(545072, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545072")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDelegateSpecialTypes()
{
await TestAsync(
@"delegate void $$F(int x);",
MainDescription("delegate void F(int x)"));
}
[WorkItem(545108, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545108")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullPointerParameter()
{
await TestAsync(
@"class C
{
unsafe void $$Goo(int* x = null)
{
}
}",
MainDescription("void C.Goo([int* x = null])"));
}
[WorkItem(545098, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545098")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestLetIdentifier1()
{
await TestInMethodAsync("var q = from e in \"\" let $$y = 1 let a = new { y } select a;",
MainDescription($"({FeaturesResources.range_variable}) int y"));
}
[WorkItem(545295, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545295")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNullableDefaultValue()
{
await TestAsync(
@"class Test
{
void $$Method(int? t1 = null)
{
}
}",
MainDescription("void Test.Method([int? t1 = null])"));
}
[WorkItem(529586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529586")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInvalidParameterInitializer()
{
await TestAsync(
@"class Program
{
void M1(float $$j1 = ""Hello""
+
""World"")
{
}
}",
MainDescription($@"({FeaturesResources.parameter}) float j1 = ""Hello"" + ""World"""));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstLocal()
{
await TestAsync(
@"class Program
{
void Main()
{
const int MEGABYTE = 1024 *
1024 + true;
Blah($$MEGABYTE);
}
}",
MainDescription($@"({FeaturesResources.local_constant}) int MEGABYTE = 1024 * 1024 + true"));
}
[WorkItem(545230, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545230")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestComplexConstField()
{
await TestAsync(
@"class Program
{
const int a = true
-
false;
void Main()
{
Goo($$a);
}
}",
MainDescription($"({FeaturesResources.constant}) int Program.a = true - false"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTypeParameterCrefDoesNotHaveQuickInfo()
{
await TestAsync(
@"class C<T>
{
/// <see cref=""C{X$$}""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref1()
{
await TestAsync(
@"class Program
{
/// <see cref=""Mai$$n""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref2()
{
await TestAsync(
@"class Program
{
/// <see cref=""$$Main""/>
static void Main(string[] args)
{
}
}",
MainDescription(@"void Program.Main(string[] args)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref3()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref4()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main$$""/>
static void Main(string[] args)
{
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref5()
{
await TestAsync(
@"class Program
{
/// <see cref=""Main""$$/>
static void Main(string[] args)
{
}
}");
}
[WorkItem(546849, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546849")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestIndexedProperty()
{
var markup = @"class Program
{
void M()
{
CCC c = new CCC();
c.Index$$Prop[0] = ""s"";
}
}";
// Note that <COMImport> is required by compiler. Bug 17013 tracks enabling indexed property for non-COM types.
var referencedCode = @"Imports System.Runtime.InteropServices
<ComImport()>
<GuidAttribute(CCC.ClassId)>
Public Class CCC
#Region ""COM GUIDs""
Public Const ClassId As String = ""9d965fd2-1514-44f6-accd-257ce77c46b0""
Public Const InterfaceId As String = ""a9415060-fdf0-47e3-bc80-9c18f7f39cf6""
Public Const EventsId As String = ""c6a866a5-5f97-4b53-a5df-3739dc8ff1bb""
# End Region
''' <summary>
''' An index property from VB
''' </summary>
''' <param name=""p1"">p1 is an integer index</param>
''' <returns>A string</returns>
Public Property IndexProp(ByVal p1 As Integer, Optional ByVal p2 As Integer = 0) As String
Get
Return Nothing
End Get
Set(ByVal value As String)
End Set
End Property
End Class";
await TestWithReferenceAsync(sourceCode: markup,
referencedCode: referencedCode,
sourceLanguage: LanguageNames.CSharp,
referencedLanguage: LanguageNames.VisualBasic,
expectedResults: MainDescription("string CCC.IndexProp[int p1, [int p2 = 0]] { get; set; }"));
}
[WorkItem(546918, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546918")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGeneric()
{
await TestAsync(
@"class A<T>
{
enum SortOrder
{
Ascending,
Descending,
None
}
void Goo()
{
var b = $$SortOrder.Ascending;
}
}",
MainDescription(@"enum A<T>.SortOrder"));
}
[WorkItem(546970, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546970")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestUnconstructedGenericInCRef()
{
await TestAsync(
@"/// <see cref=""$$C{T}"" />
class C<T>
{
}",
MainDescription(@"class C<T>"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAwaitableMethod()
{
var markup = @"using System.Threading.Tasks;
class C
{
async Task Goo()
{
Go$$o();
}
}";
var description = $"({CSharpFeaturesResources.awaitable}) Task C.Goo()";
await VerifyWithMscorlib45Async(markup, new[] { MainDescription(description) });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ObsoleteItem()
{
var markup = @"
using System;
class Program
{
[Obsolete]
public void goo()
{
go$$o();
}
}";
await TestAsync(markup, MainDescription($"[{CSharpFeaturesResources.deprecated}] void Program.goo()"));
}
[WorkItem(751070, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/751070")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DynamicOperator()
{
var markup = @"
public class Test
{
public delegate void NoParam();
static int Main()
{
dynamic x = new object();
if (((System.Func<dynamic>)(() => (x =$$= null)))())
return 0;
return 1;
}
}";
await TestAsync(markup, MainDescription("dynamic dynamic.operator ==(dynamic left, dynamic right)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment()
{
await TestAsync(
@"/// <summary>
///goo
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine()
{
await TestAsync(
@"/// <summary>
/// goo
/// bar
/// </summary>
class C$$
{
}", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref()
{
await TestAsync(
@"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
class C$$
{
}", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock()
{
await TestAsync(
@"/// red
/// <summary>
/// green
/// </summary>
/// yellow
class C$$
{
}", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NewlineAfterPara()
{
await TestAsync(
@"/// <summary>
/// <para>goo</para>
/// </summary>
class C$$
{
}", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TextOnlyDocComment_Metadata()
{
var referenced = @"
/// <summary>
///goo
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestTrimConcatMultiLine_Metadata()
{
var referenced = @"
/// <summary>
/// goo
/// bar
/// </summary>
public class C
{
}";
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("goo bar"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestCref_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"/// <summary>
/// <see cref=""C""/>
/// <seealso cref=""C""/>
/// </summary>
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("C C"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeTextOutsideSummaryBlock_Metadata()
{
var code = @"
class G
{
void goo()
{
C$$ c;
}
}";
var referenced = @"
/// red
/// <summary>
/// green
/// </summary>
/// yellow
public class C
{
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("green"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] arg$$s, T otherParam)
{
}
}", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(arg$$s: new string[] { }, 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("First parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T oth$$erParam)
{
}
}", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task Param2_Metadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Goo<int>(args: new string[] { }, other$$Param: 1);
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{ T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T>(string[] args, T otherParam)
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#", Documentation("Another parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TypeParam()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""Goo{T} (string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of C.Goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnboundCref()
{
await TestAsync(
@"/// <summary></summary>
public class C
{
/// <typeparam name=""T"">A type parameter of <see cref=""goo{T}(string[], T)""/></typeparam>
/// <param name=""args"">First parameter of <see cref=""Goo{T} (string[], T)""/></param>
/// <param name=""otherParam"">Another parameter of <see cref=""Goo{T}(string[], T)""/></param>
public void Goo<T$$>(string[] args, T otherParam)
{
}
}", Documentation("A type parameter of goo<T>(string[], T)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructor()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass$$()
{
}
}", Documentation("This sample shows how to specify the TestClass constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInConstructorOverloaded()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass""/> constructor as a cref attribute.
/// </summary>
public TestClass()
{
}
/// <summary>
/// This sample shows how to specify the <see cref=""TestClass(int)""/> constructor as a cref attribute.
/// </summary>
public TestC$$lass(int value)
{
}
}", Documentation("This sample shows how to specify the TestClass(int) constructor as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod1()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericMethod2()
{
await TestAsync(
@"public class TestClass
{
/// <summary>
/// The GetGenericValue method.
/// <para>This sample shows how to specify the <see cref=""GetGenericValue{T}(T)""/> method as a cref attribute.</para>
/// </summary>
public static T GetGenericVa$$lue<T>(T para)
{
return para;
}
}", Documentation("The GetGenericValue method.\r\n\r\nThis sample shows how to specify the TestClass.GetGenericValue<T>(T) method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading1()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValu$$e();
GetGenericValue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to specify the TestClass.GetGenericValue() method as a cref attribute."));
}
[WorkItem(813350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/813350")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInMethodOverloading2()
{
await TestAsync(
@"public class TestClass
{
public static int GetZero()
{
GetGenericValue();
GetGenericVal$$ue(5);
}
/// <summary>
/// This sample shows how to call the <see cref=""GetGenericValue{T}(T)""/> method
/// </summary>
public static T GetGenericValue<T>(T para)
{
return para;
}
/// <summary>
/// This sample shows how to specify the <see cref=""GetGenericValue""/> method as a cref attribute.
/// </summary>
public static void GetGenericValue()
{
}
}", Documentation("This sample shows how to call the TestClass.GetGenericValue<T>(T) method"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task CrefInGenericType()
{
await TestAsync(
@"/// <summary>
/// <remarks>This example shows how to specify the <see cref=""GenericClass{T}""/> cref.</remarks>
/// </summary>
class Generic$$Class<T>
{
}",
Documentation("This example shows how to specify the GenericClass<T> cref.",
ExpectedClassifications(
Text("This example shows how to specify the"),
WhiteSpace(" "),
Class("GenericClass"),
Punctuation.OpenAngle,
TypeParameter("T"),
Punctuation.CloseAngle,
WhiteSpace(" "),
Text("cref."))));
}
[WorkItem(812720, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/812720")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ClassificationOfCrefsFromMetadata()
{
var code = @"
class G
{
void goo()
{
C c;
c.Go$$o();
}
}";
var referenced = @"
/// <summary></summary>
public class C
{
/// <summary>
/// See <see cref=""Goo""/> method
/// </summary>
public void Goo()
{
}
}";
await TestWithMetadataReferenceHelperAsync(code, referenced, "C#", "C#",
Documentation("See C.Goo() method",
ExpectedClassifications(
Text("See"),
WhiteSpace(" "),
Class("C"),
Punctuation.Text("."),
Identifier("Goo"),
Punctuation.OpenParen,
Punctuation.CloseParen,
WhiteSpace(" "),
Text("method"))));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldAvailableInBothLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
int x;
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.field}) int C.x"), Usage("") });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInOneLinkedFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(37097, "https://github.com/dotnet/roslyn/issues/37097")]
public async Task BindSymbolInOtherFile()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""GOO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task FieldUnavailableInTwoLinkedFiles()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
void goo()
{
x$$
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage(
$"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}",
expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ExcludeFilesWithInactiveRegions()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""GOO,BAR"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if GOO
int x;
#endif
#if BAR
void goo()
{
x$$
}
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument"" />
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj3"" PreprocessorSymbols=""BAR"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj3", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true);
await VerifyWithReferenceWorkerAsync(markup, new[] { expectedDescription });
}
[WorkItem(962353, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/962353")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NoValidSymbolsInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void goo()
{
B$$ar();
}
#if B
void Bar() { }
#endif
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup);
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
int x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LocalWarningInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""PROJ1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
#if PROJ1
int x;
#endif
int y = x$$;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.local_variable}) int x"), Usage($"\r\n{string.Format(FeaturesResources._0_1, "Proj1", FeaturesResources.Available)}\r\n{string.Format(FeaturesResources._0_1, "Proj2", FeaturesResources.Not_Available)}\r\n\r\n{FeaturesResources.You_can_use_the_navigation_bar_to_switch_contexts}", expectsWarningGlyph: true) });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task LabelsValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void M()
{
$$LABEL: goto LABEL;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.label}) LABEL"), Usage("") });
}
[WorkItem(1020944, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1020944")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task RangeVariablesValidInLinkedDocuments()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"">
<Document FilePath=""SourceDocument""><![CDATA[
using System.Linq;
class C
{
void M()
{
var x = from y in new[] {1, 2, 3} select $$y;
}
}
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
await VerifyWithReferenceWorkerAsync(markup, new[] { MainDescription($"({FeaturesResources.range_variable}) int y"), Usage("") });
}
[WorkItem(1019766, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1019766")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PointerAccessibility()
{
var markup = @"class C
{
unsafe static void Main()
{
void* p = null;
void* q = null;
dynamic d = true;
var x = p =$$= q == d;
}
}";
await TestAsync(markup, MainDescription("bool void*.operator ==(void* left, void* right)"));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfArrayType()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<int[]> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "int[]")));
}
[WorkItem(1114300, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1114300")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task AwaitingTaskOfDynamic()
{
var markup = @"
using System.Threading.Tasks;
class Program
{
async Task<dynamic> M()
{
awa$$it M();
}
}";
await TestAsync(markup, MainDescription(string.Format(FeaturesResources.Awaited_task_returns_0, "dynamic")));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
#if ONE
void Do(int x){}
#endif
#if TWO
void Do(string x){}
#endif
void Shared()
{
this.Do$$
}
}]]></Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void C.Do(int x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.Completion)]
public async Task MethodOverloadDifferencesIgnored_ContainingType()
{
var markup = @"<Workspace>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj1"" PreprocessorSymbols=""ONE"">
<Document FilePath=""SourceDocument""><![CDATA[
class C
{
void Shared()
{
var x = GetThing().Do$$();
}
#if ONE
private Methods1 GetThing()
{
return new Methods1();
}
#endif
#if TWO
private Methods2 GetThing()
{
return new Methods2();
}
#endif
}
#if ONE
public class Methods1
{
public void Do(string x) { }
}
#endif
#if TWO
public class Methods2
{
public void Do(string x) { }
}
#endif
]]>
</Document>
</Project>
<Project Language=""C#"" CommonReferences=""true"" AssemblyName=""Proj2"" PreprocessorSymbols=""TWO"">
<Document IsLinkFile=""true"" LinkAssemblyName=""Proj1"" LinkFilePath=""SourceDocument""/>
</Project>
</Workspace>";
var expectedDescription = $"void Methods1.Do(string x)";
await VerifyWithReferenceWorkerAsync(markup, MainDescription(expectedDescription));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(4868, "https://github.com/dotnet/roslyn/issues/4868")]
public async Task QuickInfoExceptions()
{
await TestAsync(
@"using System;
namespace MyNs
{
class MyException1 : Exception
{
}
class MyException2 : Exception
{
}
class TestClass
{
/// <exception cref=""MyException1""></exception>
/// <exception cref=""T:MyNs.MyException2""></exception>
/// <exception cref=""System.Int32""></exception>
/// <exception cref=""double""></exception>
/// <exception cref=""Not_A_Class_But_Still_Displayed""></exception>
void M()
{
M$$();
}
}
}",
Exceptions($"\r\n{WorkspacesResources.Exceptions_colon}\r\n MyException1\r\n MyException2\r\n int\r\n double\r\n Not_A_Class_But_Still_Displayed"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$();
void local() { i++; this.M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
local$$(i);
void local(int j) { j++; M(); }
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLocalFunction3()
{
await TestAsync(@"
class C
{
public void M(int @this)
{
int i = 0;
local$$();
void local()
{
M(1);
i++;
@this++;
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction4()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction$$()
{
int local = 0;
int InnerLocalFunction()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
void OuterLocalFunction()
{
int local = 0;
int InnerLocalFunction$$()
{
field++;
return local;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction$$()
{
_ = local1;
void InnerLocalFunction()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLocalFunction7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
void OuterLocalFunction()
{
_ = local1;
void InnerLocalFunction$$()
{
_ = local2;
}
}
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action a = () =$$> { i++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Action<int> a = j =$$> { i++; j++; M(); };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda2_DifferentOrder()
{
await TestAsync(@"
class C
{
void M(int j)
{
int i;
System.Action a = () =$$> { M(); i++; j++; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, j, i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda3()
{
await TestAsync(@"
class C
{
void M()
{
int i;
int @this;
N(() =$$> { M(); @this++; }, () => { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, @this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnLambda4()
{
await TestAsync(@"
class C
{
void M()
{
int i;
N(() => { M(); }, () =$$> { i++; });
}
void N(System.Action x, System.Action y) { }
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda5()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =$$>
{
int local = 0;
System.Func<int> b = () =>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda6()
{
await TestAsync(@"
class C
{
int field;
void M()
{
System.Action a = () =>
{
int local = 0;
System.Func<int> b = () =$$>
{
field++;
return local;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} this, local"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda7()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =$$>
{
_ = local1;
System.Action b = () =>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local1, local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(26101, "https://github.com/dotnet/roslyn/issues/26101")]
public async Task QuickInfoCapturesOnLambda8()
{
await TestAsync(@"
class C
{
int field;
void M()
{
int local1 = 0;
int local2 = 0;
System.Action a = () =>
{
_ = local1;
System.Action b = () =$$>
{
_ = local2;
};
};
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} local2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(23307, "https://github.com/dotnet/roslyn/issues/23307")]
public async Task QuickInfoCapturesOnDelegate()
{
await TestAsync(@"
class C
{
void M()
{
int i;
System.Func<bool, int> f = dele$$gate(bool b) { i++; return 1; };
}
}",
Captures($"\r\n{WorkspacesResources.Variables_captured_colon} i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(1516, "https://github.com/dotnet/roslyn/issues/1516")]
public async Task QuickInfoWithNonStandardSeeAttributesAppear()
{
await TestAsync(
@"class C
{
/// <summary>
/// <see cref=""System.String"" />
/// <see href=""http://microsoft.com"" />
/// <see langword=""null"" />
/// <see unsupported-attribute=""cat"" />
/// </summary>
void M()
{
M$$();
}
}",
Documentation(@"string http://microsoft.com null cat"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(6657, "https://github.com/dotnet/roslyn/issues/6657")]
public async Task OptionalParameterFromPreviousSubmission()
{
const string workspaceDefinition = @"
<Workspace>
<Submission Language=""C#"" CommonReferences=""true"">
void M(int x = 1) { }
</Submission>
<Submission Language=""C#"" CommonReferences=""true"">
M(x$$: 2)
</Submission>
</Workspace>
";
using var workspace = TestWorkspace.Create(XElement.Parse(workspaceDefinition), workspaceKind: WorkspaceKind.Interactive);
await TestWithOptionsAsync(workspace, MainDescription($"({ FeaturesResources.parameter }) int x = 1"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TupleProperty()
{
await TestInMethodAsync(
@"interface I
{
(int, int) Name { get; set; }
}
class C : I
{
(int, int) I.Name$$
{
get
{
throw new System.Exception();
}
set
{
}
}
}",
MainDescription("(int, int) C.Name { get; set; }"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create();
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity0ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create();
}
}
",
MainDescription("struct System.ValueTuple"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) ValueTuple<int> y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity1ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1);
}
}
",
MainDescription("struct System.ValueTuple<System.Int32>"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2VariableName()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var y$$ = ValueTuple.Create(1, 1);
}
}
",
MainDescription($"({ FeaturesResources.local_variable }) (int, int) y"));
}
[WorkItem(18311, "https://github.com/dotnet/roslyn/issues/18311")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task ValueTupleWithArity2ImplicitVar()
{
await TestAsync(
@"
using System;
public class C
{
void M()
{
var$$ y = ValueTuple.Create(1, 1);
}
}
",
MainDescription("(System.Int32, System.Int32)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefMethod()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int i = ref $$goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription("ref int Program.goo()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLocal()
{
await TestInMethodAsync(
@"using System;
class Program
{
static void Main(string[] args)
{
ref int $$i = ref goo();
}
private static ref int goo()
{
throw new NotImplementedException();
}
}",
MainDescription($"({FeaturesResources.local_variable}) ref int i"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(410932, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=410932")]
public async Task TestGenericMethodInDocComment()
{
await TestAsync(
@"
class Test
{
T F<T>()
{
F<T>();
}
/// <summary>
/// <see cref=""F$${T}()""/>
/// </summary>
void S()
{ }
}
",
MainDescription("T Test.F<T>()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(403665, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=403665&_a=edit")]
public async Task TestExceptionWithCrefToConstructorDoesNotCrash()
{
await TestAsync(
@"
class Test
{
/// <summary>
/// </summary>
/// <exception cref=""Test.Test""/>
public Test$$() {}
}
",
MainDescription("Test.Test()"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct()
{
var markup = "ref struct X$$ {}";
await TestAsync(markup, MainDescription("ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefStruct_Nested()
{
var markup = @"
namespace Nested
{
ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("ref struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct()
{
var markup = "readonly struct X$$ {}";
await TestAsync(markup, MainDescription("readonly struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly struct Nested.X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct()
{
var markup = "readonly ref struct X$$ {}";
await TestAsync(markup, MainDescription("readonly ref struct X"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestReadOnlyRefStruct_Nested()
{
var markup = @"
namespace Nested
{
readonly ref struct X$$ {}
}";
await TestAsync(markup, MainDescription("readonly ref struct Nested.X"));
}
[WorkItem(22450, "https://github.com/dotnet/roslyn/issues/22450")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestRefLikeTypesNoDeprecated()
{
var xmlString = @"
<Workspace>
<Project Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<MetadataReferenceFromSource Language=""C#"" LanguageVersion=""7.2"" CommonReferences=""true"">
<Document FilePath=""ReferencedDocument"">
public ref struct TestRef
{
}
</Document>
</MetadataReferenceFromSource>
<Document FilePath=""SourceDocument"">
ref struct Test
{
private $$TestRef _field;
}
</Document>
</Project>
</Workspace>";
// There should be no [deprecated] attribute displayed.
await VerifyWithReferenceWorkerAsync(xmlString, MainDescription($"ref struct TestRef"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType()
{
await TestAsync(
@"namespace ConsoleApplication1
{
class Program
{
static A B { get; set; }
static B A { get; set; }
static void Main(string[] args)
{
B = ConsoleApplication1.B$$.F();
}
}
class A { }
class B
{
public static A F() => null;
}
}",
MainDescription($"ConsoleApplication1.A ConsoleApplication1.B.F()"));
}
[WorkItem(2644, "https://github.com/dotnet/roslyn/issues/2644")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task PropertyWithSameNameAsOtherType2()
{
await TestAsync(
@"using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
public static List<Bar> Bar { get; set; }
static void Main(string[] args)
{
Tes$$t<Bar>();
}
static void Test<T>() { }
}
class Bar
{
}
}",
MainDescription($"void Program.Test<Bar>()"));
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_01()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b.Content$$Type, out var chars)
{
}
}
}
");
}
[WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task InMalformedEmbeddedStatement_02()
{
await TestAsync(
@"
class Program
{
void method1()
{
if (method2())
.Any(b => b$$.ContentType, out var chars)
{
}
}
}
",
MainDescription($"({ FeaturesResources.parameter }) ? b"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task EnumConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Enum
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Enum"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.Delegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : Delegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task MulticastDelegateConstraint()
{
await TestInMethodAsync(
@"
class X<T> where T : System.MulticastDelegate
{
private $$T x;
}",
MainDescription($"T {FeaturesResources.in_} X<T> where T : MulticastDelegate"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : unmanaged
{
}",
MainDescription("class X<T> where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : unmanaged { }
}",
MainDescription("void X.M<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : unmanaged;",
MainDescription("delegate void D<T>() where T : unmanaged"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task UnmanagedConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : unmanaged { }
}
}",
MainDescription("void M<T>() where T : unmanaged"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestGetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { g$$et; set; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestSetAccessorDocumentation()
{
await TestAsync(
@"
class X
{
/// <summary>Summary for property Goo</summary>
int Goo { get; s$$et; }
}",
Documentation("Summary for property Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
a$$dd => throw null;
remove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventAddDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo +$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation1()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo
{
add => throw null;
r$$emove => throw null;
}
}",
Documentation("Summary for event Goo"));
}
[WorkItem(29703, "https://github.com/dotnet/roslyn/issues/29703")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestEventRemoveDocumentation2()
{
await TestAsync(
@"
using System;
class X
{
/// <summary>Summary for event Goo</summary>
event EventHandler<EventArgs> Goo;
void M() => Goo -$$= null;
}",
Documentation("Summary for event Goo"));
}
[WorkItem(30642, "https://github.com/dotnet/roslyn/issues/30642")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task BuiltInOperatorWithUserDefinedEquivalent()
{
await TestAsync(
@"
class X
{
void N(string a, string b)
{
var v = a $$== b;
}
}",
MainDescription("bool string.operator ==(string a, string b)"),
SymbolGlyph(Glyph.Operator));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Type()
{
await TestAsync(
@"
class $$X<T> where T : notnull
{
}",
MainDescription("class X<T> where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Method()
{
await TestAsync(
@"
class X
{
void $$M<T>() where T : notnull { }
}",
MainDescription("void X.M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_Delegate()
{
await TestAsync(
"delegate void $$D<T>() where T : notnull;",
MainDescription("delegate void D<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NotNullConstraint_LocalFunction()
{
await TestAsync(
@"
class X
{
void N()
{
void $$M<T>() where T : notnull { }
}
}",
MainDescription("void M<T>() where T : notnull"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableParameterThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
void N(string? s)
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.parameter}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableFieldThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? s = null;
void N()
{
s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.field}) string? X.s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullablePropertyThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
class X
{
string? S { get; set; }
void N()
{
S = """";
string s2 = $$S;
}
}",
MainDescription("string? X.S { get; set; }"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "S")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string?> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableRangeVariableThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
IEnumerable<string> enumerable;
foreach (var s in enumerable)
{
string s2 = $$s;
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsMaybeNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = null;
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_may_be_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableLocalThatIsNotNull()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string? s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownPriorToLanguageVersion8()
{
await TestWithOptionsAsync(TestOptions.Regular7_3,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownInNullableDisable()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable disable
using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableShownWhenEnabledGlobally()
{
await TestWithOptionsAsync(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, nullableContextOptions: NullableContextOptions.Enable),
@"using System.Collections.Generic;
class X
{
void N()
{
string s = """";
string s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_variable}) string s"),
NullabilityAnalysis(string.Format(FeaturesResources._0_is_not_null_here, "s")));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForValueType()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
int a = 0;
int b = $$a;
}
}",
MainDescription($"({FeaturesResources.local_variable}) int a"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task NullableNotShownForConst()
{
await TestWithOptionsAsync(TestOptions.Regular8,
@"#nullable enable
using System.Collections.Generic;
class X
{
void N()
{
const string? s = null;
string? s2 = $$s;
}
}",
MainDescription($"({FeaturesResources.local_constant}) string? s = null"),
NullabilityAnalysis(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocInlineSummary()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels1()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <inheritdoc cref=""M()""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocTwoLevels2()
{
var markup =
@"
/// <summary>Summary documentation</summary>
/// <remarks>Remarks documentation</remarks>
void M() { }
/// <summary><inheritdoc cref=""M()""/></summary>
void M(int x) { }
/// <summary><inheritdoc cref=""M(int)""/></summary>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation("Summary documentation"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocWithTypeParamRef()
{
var markup =
@"
public class Program
{
public static void Main() => _ = new Test<int>().$$Clone();
}
public class Test<T> : ICloneable<Test<T>>
{
/// <inheritdoc/>
public Test<T> Clone() => new();
}
/// <summary>A type that has clonable instances.</summary>
/// <typeparam name=""T"">The type of instances that can be cloned.</typeparam>
public interface ICloneable<T>
{
/// <summary>Clones a <typeparamref name=""T""/>.</summary>
/// <returns>A clone of the <typeparamref name=""T""/>.</returns>
public T Clone();
}";
await TestInClassAsync(markup,
MainDescription("Test<int> Test<int>.Clone()"),
Documentation("Clones a Test<T>."));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle1()
{
var markup =
@"
/// <inheritdoc cref=""M(int, int)""/>
void M(int x) { }
/// <inheritdoc cref=""M(int)""/>
void $$M(int x, int y) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x, int y)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle2()
{
var markup =
@"
/// <inheritdoc cref=""M(int)""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestInheritdocCycle3()
{
var markup =
@"
/// <inheritdoc cref=""M""/>
void $$M(int x) { }";
await TestInClassAsync(markup,
MainDescription("void C.M(int x)"),
Documentation(""));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38794, "https://github.com/dotnet/roslyn/issues/38794")]
public async Task TestLinqGroupVariableDeclaration()
{
var code =
@"
void M(string[] a)
{
var v = from x in a
group x by x.Length into $$g
select g;
}";
await TestInClassAsync(code,
MainDescription($"({FeaturesResources.range_variable}) IGrouping<int, string> g"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerCloseBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()[5$$];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexerOpenBracket()
{
await TestAsync(@"
class C
{
public int this[int x] { get { return 1; } }
void M()
{
var x = new C()$$[5];
}
}",
MainDescription("int C.this[int x] { get; }"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(38283, "https://github.com/dotnet/roslyn/issues/38283")]
public async Task QuickInfoOnIndexer_NotOnArrayAccess()
{
await TestAsync(@"
class Program
{
void M()
{
int[] x = new int[4];
int y = x[3$$];
}
}",
MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithRemarksOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <remarks>
/// Remarks text
/// </remarks>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Remarks("\r\nRemarks text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithReturnsOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <returns>
/// Returns text
/// </returns>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Returns($"\r\n{FeaturesResources.Returns_colon}\r\n Returns text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnMethod()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M()
{
return $$M();
}
}",
MainDescription("int Program.M()"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(31618, "https://github.com/dotnet/roslyn/issues/31618")]
public async Task QuickInfoWithValueOnPropertyAccessor()
{
await TestAsync(@"
class Program
{
/// <summary>
/// Summary text
/// </summary>
/// <value>
/// Value text
/// </value>
int M { $$get; }
}",
MainDescription("int Program.M.get"),
Documentation("Summary text"),
Value($"\r\n{FeaturesResources.Value_colon}\r\n Value text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is not $$Person p)
{
}
}
}",
MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoNotPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$not Person p)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern1()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is $$Person or int)
{
}
}
}", MainDescription("class Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern2()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person or $$int)
{
}
}
}", MainDescription("struct System.Int32"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(42368, "https://github.com/dotnet/roslyn/issues/42368")]
public async Task QuickInfoOrPattern3()
{
await TestAsync(@"
class Person
{
void Goo(object o)
{
if (o is Person $$or int)
{
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoDerivedRecord()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record Person(string First, string Last)
{
}
record Student(string Id)
{
void M($$Student p)
{
}
}
", MainDescription("record Student"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(44904, "https://github.com/dotnet/roslyn/issues/44904")]
public async Task QuickInfoRecord_BaseTypeList()
{
await TestAsync(@"
record Person(string First, string Last);
record Student(int Id) : $$Person(null, null);
", MainDescription("Person.Person(string First, string Last)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfo_BaseConstructorInitializer()
{
await TestAsync(@"
public class Person { public Person(int id) { } }
public class Student : Person { public Student() : $$base(0) { } }
", MainDescription("Person.Person(int id)"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordClass()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record class Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoReadOnlyRecordStruct()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"readonly record struct Person(string First, string Last)
{
void M($$Person p)
{
}
}", MainDescription("readonly record struct Person"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
[WorkItem(51615, "https://github.com/dotnet/roslyn/issues/51615")]
public async Task TestVarPatternOnVarKeyword()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is va$$r x && x.Length > 0)
{
}
}
}",
MainDescription("class System.String"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestVarPatternOnVariableItself()
{
await TestAsync(
@"class C
{
string M() { }
void M2()
{
if (M() is var x$$ && x.Length > 0)
{
}
}
}",
MainDescription($"({FeaturesResources.local_variable}) string? x"));
}
[WorkItem(53135, "https://github.com/dotnet/roslyn/issues/53135")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestDocumentationCData()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// summary for interface IGoo
/// <code><![CDATA[
/// List<string> y = null;
/// ]]></code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"summary for interface IGoo
List<string> y = null;"));
}
[WorkItem(37503, "https://github.com/dotnet/roslyn/issues/37503")]
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task DoNotNormalizeWhitespaceForCode()
{
var markup =
@"using I$$ = IGoo;
/// <summary>
/// Normalize this, and <c>Also this</c>
/// <code>
/// line 1
/// line 2
/// </code>
/// </summary>
interface IGoo { }";
await TestAsync(markup,
MainDescription("interface IGoo"),
Documentation(@"Normalize this, and Also this
line 1
line 2"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ImplicitImplementation_FromReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
public static void M1() { }
}
class R
{
public static void M() { C1_1.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_FromTypeParameterReference()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class R
{
public static void M<T>() where T : I1 { T.$$M1(); }
}
";
await TestAsync(
code,
MainDescription("void I1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ImplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
public static void $$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestStaticAbstract_ExplicitInheritdoc_ExplicitImplementation()
{
var code = @"
interface I1
{
/// <summary>Summary text</summary>
static abstract void M1();
}
class C1_1 : I1
{
/// <inheritdoc/>
static void I1.$$M1() { }
}
";
await TestAsync(
code,
MainDescription("void C1_1.M1()"),
Documentation("Summary text"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_01()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class Program
{
System.Delegate D = bo$$ol () => true;
}",
MainDescription("struct System.Boolean"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_02()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A
{
struct B { }
System.Delegate D = A.B$$ () => null;
}",
MainDescription("struct A.B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task QuickInfoLambdaReturnType_03()
{
await TestWithOptionsAsync(
Options.Regular.WithLanguageVersion(LanguageVersion.CSharp9),
@"class A<T>
{
}
struct B
{
System.Delegate D = A<B$$> () => null;
}",
MainDescription("struct B"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestNormalFuncSynthesizedLambdaType()
{
await TestAsync(
@"class C
{
void M()
{
$$var v = (int i) => i.ToString();
}
}",
MainDescription("delegate TResult System.Func<in T, out TResult>(T arg)"),
TypeParameterMap($@"
T {FeaturesResources.is_} int
TResult {FeaturesResources.is_} string"));
}
[Fact, Trait(Traits.Feature, Traits.Features.QuickInfo)]
public async Task TestAnonymousSynthesizedLambdaType()
{
await TestAsync(
@"class C
{
void M()
{
$$var v = (ref int i) => i.ToString();
}
}",
MainDescription("delegate string <anonymous delegate>(ref int)"));
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Features/CSharp/Portable/Completion/CompletionProviders/Scripting/ReferenceDirectiveCompletionProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
[ExportCompletionProvider(nameof(ReferenceDirectiveCompletionProvider), LanguageNames.CSharp)]
[ExtensionOrder(After = nameof(LoadDirectiveCompletionProvider))]
[Shared]
internal sealed class ReferenceDirectiveCompletionProvider : AbstractReferenceDirectiveCompletionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ReferenceDirectiveCompletionProvider()
{
}
protected override string DirectiveName => "r";
protected override bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken) =>
DirectiveCompletionProviderUtilities.TryGetStringLiteralToken(tree, position, SyntaxKind.ReferenceDirectiveTrivia, out stringLiteral, cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.Completion;
using Microsoft.CodeAnalysis.Completion.Providers;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.Completion.Providers
{
[ExportCompletionProvider(nameof(ReferenceDirectiveCompletionProvider), LanguageNames.CSharp)]
[ExtensionOrder(After = nameof(LoadDirectiveCompletionProvider))]
[Shared]
internal sealed class ReferenceDirectiveCompletionProvider : AbstractReferenceDirectiveCompletionProvider
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public ReferenceDirectiveCompletionProvider()
{
}
protected override string DirectiveName => "r";
protected override bool TryGetStringLiteralToken(SyntaxTree tree, int position, out SyntaxToken stringLiteral, CancellationToken cancellationToken) =>
DirectiveCompletionProviderUtilities.TryGetStringLiteralToken(tree, position, SyntaxKind.ReferenceDirectiveTrivia, out stringLiteral, cancellationToken);
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/VisualBasic/RenameTracking/BasicRenameTrackingLanguageHeuristicsService.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking
<ExportLanguageService(GetType(IRenameTrackingLanguageHeuristicsService), LanguageNames.VisualBasic), [Shared]>
Friend NotInheritable Class BasicRenameTrackingLanguageHeuristicsService
Implements IRenameTrackingLanguageHeuristicsService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function IsIdentifierValidForRenameTracking(name As String) As Boolean Implements IRenameTrackingLanguageHeuristicsService.IsIdentifierValidForRenameTracking
Return True
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Composition
Imports Microsoft.CodeAnalysis.Editor.Implementation.RenameTracking
Imports Microsoft.CodeAnalysis.Host.Mef
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.RenameTracking
<ExportLanguageService(GetType(IRenameTrackingLanguageHeuristicsService), LanguageNames.VisualBasic), [Shared]>
Friend NotInheritable Class BasicRenameTrackingLanguageHeuristicsService
Implements IRenameTrackingLanguageHeuristicsService
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Public Function IsIdentifierValidForRenameTracking(name As String) As Boolean Implements IRenameTrackingLanguageHeuristicsService.IsIdentifierValidForRenameTracking
Return True
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class LambdaTests : CSharpTestBase
{
[Fact, WorkItem(37456, "https://github.com/dotnet/roslyn/issues/37456")]
public void Verify37456()
{
var comp = CreateCompilation(@"
using System;
using System.Collections.Generic;
using System.Linq;
public static partial class EnumerableEx
{
public static void Join1<TA, TKey, T>(this IEnumerable<TA> a, Func<TA, TKey> aKey, Func<TA, T> aSel, Func<TA, TA, T> sel)
{
KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v);
_ = a.GroupJoin(a, aKey, aKey, (f, ss) => Pair(f, ss.Select(s => Pair(true, s)))); // simplified repro
}
public static IEnumerable<T> Join2<TA, TB, TKey, T>(this IEnumerable<TA> a, IEnumerable<TB> b, Func<TA, TKey> aKey, Func<TB, TKey> bKey, Func<TA, T> aSel, Func<TA, TB, T> sel, IEqualityComparer<TKey> comp)
{
KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v);
return
from j in a.GroupJoin(b, aKey, bKey, (f, ss) => Pair(f, from s in ss select Pair(true, s)), comp)
from s in j.Value.DefaultIfEmpty()
select s.Key ? sel(j.Key, s.Value) : aSel(j.Key);
}
}");
comp.VerifyDiagnostics();
CompileAndVerify(comp);
// emitting should not hang
}
[Fact, WorkItem(608181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608181")]
public void BadInvocationInLambda()
{
var src = @"
using System;
using System.Linq.Expressions;
class C
{
Expression<Action<dynamic>> e = x => new object[](x);
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(src);
comp.VerifyDiagnostics(
// (7,52): error CS1586: Array creation must have array size or array initializer
// Expression<Action<dynamic>> e = x => new object[](x);
Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52)
);
}
[Fact]
public void TestLambdaErrors01()
{
var comp = CreateCompilationWithMscorlib40AndSystemCore(@"
using System;
using System.Linq.Expressions;
namespace System.Linq.Expressions
{
public class Expression<T> {}
}
class C
{
delegate void D1(ref int x, out int y, int z);
delegate void D2(out int x);
void M()
{
int q1 = ()=>1;
int q2 = delegate { return 1; };
Func<int> q3 = x3=>1;
Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type
Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type
D1 q6 = (double x6, ref int y6, ref int z6)=>1;
// COMPATIBILITY: The C# 4 compiler produces two errors:
//
// error CS1676: Parameter 2 must be declared with the 'out' keyword
// error CS1688: Cannot convert anonymous method block without a parameter list
// to delegate type 'D1' because it has one or more out parameters
//
// This seems redundant (because there is no 'parameter 2' in the source code)
// I propose that we eliminate the first error.
D1 q7 = delegate {};
Frob q8 = ()=>{};
D2 q9 = x9=>{};
D1 q10 = (x10,y10,z10)=>{};
// COMPATIBILITY: The C# 4 compiler produces two errors:
//
// error CS0127: Since 'System.Action' returns void, a return keyword must
// not be followed by an object expression
//
// error CS1662: Cannot convert lambda expression to delegate type 'System.Action'
// because some of the return types in the block are not implicitly convertible to
// the delegate return type
//
// The problem is adequately characterized by the first message; I propose we
// eliminate the second, which seems both redundant and wrong.
Action q11 = ()=>{ return 1; };
Action q12 = ()=>1;
Func<int> q13 = ()=>{ if (false) return 1; };
Func<int> q14 = ()=>123.456;
// Note that the type error is still an error even if the offending
// return is unreachable.
Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
// In the native compiler these errors were caught at parse time. In Roslyn, these are now semantic
// analysis errors. See changeset 1674 for details.
Action<int[]> q16 = delegate (params int[] p) { };
Action<string[]> q17 = (params string[] s)=>{};
Action<int, double[]> q18 = (int x, params double[] s)=>{};
object q19 = new Action( (int x)=>{} );
Expression<int> ex1 = ()=>1;
}
}");
comp.VerifyDiagnostics(
// (16,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type
// int q1 = ()=>1;
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "()=>1").WithArguments("lambda expression", "int").WithLocation(16, 18),
// (17,18): error CS1660: Cannot convert anonymous method to type 'int' because it is not a delegate type
// int q2 = delegate { return 1; };
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate { return 1; }").WithArguments("anonymous method", "int").WithLocation(17, 18),
// (18,24): error CS1593: Delegate 'Func<int>' does not take 1 arguments
// Func<int> q3 = x3=>1;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "x3=>1").WithArguments("System.Func<int>", "1").WithLocation(18, 24),
// (19,37): error CS0234: The type or namespace name 'Itn23' does not exist in the namespace 'System' (are you missing an assembly reference?)
// Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Itn23").WithArguments("Itn23", "System").WithLocation(19, 37),
// (20,35): error CS0234: The type or namespace name 'Duobel' does not exist in the namespace 'System' (are you missing an assembly reference?)
// Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Duobel").WithArguments("Duobel", "System").WithLocation(20, 35),
// (20,27): error CS1593: Delegate 'Func<double>' does not take 1 arguments
// Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(System.Duobel x5)=>1").WithArguments("System.Func<double>", "1").WithLocation(20, 27),
// (21,17): error CS1661: Cannot convert lambda expression to delegate type 'C.D1' because the parameter types do not match the delegate parameter types
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double x6, ref int y6, ref int z6)=>1").WithArguments("lambda expression", "C.D1").WithLocation(21, 17),
// (21,25): error CS1678: Parameter 1 is declared as type 'double' but should be 'ref int'
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_BadParamType, "x6").WithArguments("1", "", "double", "ref ", "int").WithLocation(21, 25),
// (21,37): error CS1676: Parameter 2 must be declared with the 'out' keyword
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_BadParamRef, "y6").WithArguments("2", "out").WithLocation(21, 37),
// (21,49): error CS1677: Parameter 3 should not be declared with the 'ref' keyword
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_BadParamExtraRef, "z6").WithArguments("3", "ref").WithLocation(21, 49),
// (32,17): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'C.D1' because it has one or more out parameters
// D1 q7 = delegate {};
Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, "delegate {}").WithArguments("C.D1").WithLocation(32, 17),
// (34,9): error CS0246: The type or namespace name 'Frob' could not be found (are you missing a using directive or an assembly reference?)
// Frob q8 = ()=>{};
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Frob").WithArguments("Frob").WithLocation(34, 9),
// (36,17): error CS1676: Parameter 1 must be declared with the 'out' keyword
// D2 q9 = x9=>{};
Diagnostic(ErrorCode.ERR_BadParamRef, "x9").WithArguments("1", "out").WithLocation(36, 17),
// (38,19): error CS1676: Parameter 1 must be declared with the 'ref' keyword
// D1 q10 = (x10,y10,z10)=>{};
Diagnostic(ErrorCode.ERR_BadParamRef, "x10").WithArguments("1", "ref").WithLocation(38, 19),
// (38,23): error CS1676: Parameter 2 must be declared with the 'out' keyword
// D1 q10 = (x10,y10,z10)=>{};
Diagnostic(ErrorCode.ERR_BadParamRef, "y10").WithArguments("2", "out").WithLocation(38, 23),
// (52,28): error CS8030: Anonymous function converted to a void returning delegate cannot return a value
// Action q11 = ()=>{ return 1; };
Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(52, 28),
// (54,26): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action q12 = ()=>1;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(54, 26),
// (56,42): warning CS0162: Unreachable code detected
// Func<int> q13 = ()=>{ if (false) return 1; };
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(56, 42),
// (56,27): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>'
// Func<int> q13 = ()=>{ if (false) return 1; };
Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(56, 27),
// (58,29): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
// Func<int> q14 = ()=>123.456;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "123.456").WithArguments("double", "int").WithLocation(58, 29),
// (58,29): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<int> q14 = ()=>123.456;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "123.456").WithArguments("lambda expression").WithLocation(58, 29),
// (62,51): error CS0266: Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?)
// Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1m").WithArguments("decimal", "double").WithLocation(62, 51),
// (62,51): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1m").WithArguments("lambda expression").WithLocation(62, 51),
// (62,44): warning CS0162: Unreachable code detected
// Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(62, 44),
// (66,39): error CS1670: params is not valid in this context
// Action<int[]> q16 = delegate (params int[] p) { };
Diagnostic(ErrorCode.ERR_IllegalParams, "params int[] p").WithLocation(66, 39),
// (67,33): error CS1670: params is not valid in this context
// Action<string[]> q17 = (params string[] s)=>{};
Diagnostic(ErrorCode.ERR_IllegalParams, "params string[] s").WithLocation(67, 33),
// (68,45): error CS1670: params is not valid in this context
// Action<int, double[]> q18 = (int x, params double[] s)=>{};
Diagnostic(ErrorCode.ERR_IllegalParams, "params double[] s").WithLocation(68, 45),
// (70,34): error CS1593: Delegate 'Action' does not take 1 arguments
// object q19 = new Action( (int x)=>{} );
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int x)=>{}").WithArguments("System.Action", "1").WithLocation(70, 34),
// (72,9): warning CS0436: The type 'Expression<T>' in '' conflicts with the imported type 'Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// Expression<int> ex1 = ()=>1;
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<int>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>").WithLocation(72, 9),
// (72,31): error CS0835: Cannot convert lambda to an expression tree whose type argument 'int' is not a delegate type
// Expression<int> ex1 = ()=>1;
Diagnostic(ErrorCode.ERR_ExpressionTreeMustHaveDelegate, "()=>1").WithArguments("int").WithLocation(72, 31)
);
}
[Fact] // 5368
public void TestLambdaErrors02()
{
string code = @"
class C
{
void M()
{
System.Func<int, int> del = x => x + 1;
}
}";
var compilation = CreateCompilation(code);
compilation.VerifyDiagnostics(); // no errors expected
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[Fact]
public void TestLambdaErrors03()
{
string source = @"
using System;
interface I : IComparable<IComparable<I>> { }
class C
{
static void Goo(Func<IComparable<I>> x) { }
static void Goo(Func<I> x) {}
static void M()
{
Goo(() => null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(Func<IComparable<I>>)' and 'C.Goo(Func<I>)'
// Goo(() => null);
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(System.Func<System.IComparable<I>>)", "C.Goo(System.Func<I>)").WithLocation(12, 9));
}
[WorkItem(18645, "https://github.com/dotnet/roslyn/issues/18645")]
[Fact]
public void LambdaExpressionTreesErrors()
{
string source = @"
using System;
using System.Linq.Expressions;
class C
{
void M()
{
Expression<Func<int,int>> ex1 = () => 1;
Expression<Func<int,int>> ex2 = (double d) => 1;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,41): error CS1593: Delegate 'Func<int, int>' does not take 0 arguments
// Expression<Func<int,int>> ex1 = () => 1;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => 1").WithArguments("System.Func<int, int>", "0").WithLocation(9, 41),
// (10,41): error CS1661: Cannot convert lambda expression to type 'Expression<Func<int, int>>' because the parameter types do not match the delegate parameter types
// Expression<Func<int,int>> ex2 = (double d) => 1;
Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double d) => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int, int>>").WithLocation(10, 41),
// (10,49): error CS1678: Parameter 1 is declared as type 'double' but should be 'int'
// Expression<Func<int,int>> ex2 = (double d) => 1;
Diagnostic(ErrorCode.ERR_BadParamType, "d").WithArguments("1", "", "double", "", "int").WithLocation(10, 49));
}
[WorkItem(539976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539976")]
[Fact]
public void LambdaArgumentToOverloadedDelegate()
{
var text = @"class W
{
delegate T Func<A0, T>(A0 a0);
static int F(Func<short, int> f) { return 0; }
static int F(Func<short, double> f) { return 1; }
static int Main()
{
return F(c => c);
}
}
";
var comp = CreateCompilation(Parse(text));
comp.VerifyDiagnostics();
}
[WorkItem(528044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528044")]
[Fact]
public void MissingReferenceInOverloadResolution()
{
var text1 = @"
using System;
public static class A
{
public static void Goo(Func<B, object> func) { }
public static void Goo(Func<C, object> func) { }
}
public class B
{
public Uri GetUrl()
{
return null;
}
}
public class C
{
public string GetUrl()
{
return null;
}
}";
var comp1 = CreateCompilationWithMscorlib40(
new[] { Parse(text1) },
new[] { TestMetadata.Net451.System });
var text2 = @"
class Program
{
static void Main()
{
A.Goo(x => x.GetUrl());
}
}
";
var comp2 = CreateCompilationWithMscorlib40(
new[] { Parse(text2) },
new[] { new CSharpCompilationReference(comp1) });
Assert.Equal(0, comp2.GetDiagnostics().Count());
}
[WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")]
[Fact()]
public void OverloadResolutionWithEmbeddedInteropType()
{
var text1 = @"
using System;
using System.Collections.Generic;
using stdole;
public static class A
{
public static void Goo(Func<X> func)
{
System.Console.WriteLine(""X"");
}
public static void Goo(Func<Y> func)
{
System.Console.WriteLine(""Y"");
}
}
public delegate void X(List<IDispatch> addin);
public delegate void Y(List<string> addin);
";
var comp1 = CreateCompilation(
Parse(text1),
new[] { TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) },
options: TestOptions.ReleaseDll);
var text2 = @"
public class Program
{
public static void Main()
{
A.Goo(() => delegate { });
}
}
";
var comp2 = CreateCompilation(
Parse(text2),
new MetadataReference[]
{
new CSharpCompilationReference(comp1),
TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true)
},
options: TestOptions.ReleaseExe);
CompileAndVerify(comp2, expectedOutput: "Y").Diagnostics.Verify();
var comp3 = CreateCompilation(
Parse(text2),
new MetadataReference[]
{
comp1.EmitToImageReference(),
TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true)
},
options: TestOptions.ReleaseExe);
CompileAndVerify(comp3, expectedOutput: "Y").Diagnostics.Verify();
}
[WorkItem(6358, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidExpressionInvolveLambdaOperator()
{
var text1 = @"
class C
{
static void X()
{
int x=0; int y=0;
if(x-=>*y) // CS1525
return;
return;
}
}
";
var comp = CreateCompilation(Parse(text1));
var errs = comp.GetDiagnostics();
Assert.True(0 < errs.Count(), "Diagnostics not empty");
Assert.True(0 < errs.Where(e => e.Code == 1525).Select(e => e).Count(), "Diagnostics contains CS1525");
}
[WorkItem(540219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540219")]
[Fact]
public void OverloadResolutionWithStaticType()
{
var vbSource = @"
Imports System
Namespace Microsoft.VisualBasic.CompilerServices
<System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)>
Public NotInheritable Class StandardModuleAttribute
Inherits System.Attribute
Public Sub New()
MyBase.New()
End Sub
End Class
End Namespace
Public Module M
Sub Goo(x as Action(Of String))
End Sub
Sub Goo(x as Action(Of GC))
End Sub
End Module
";
var vbProject = VisualBasic.VisualBasicCompilation.Create(
"VBProject",
references: new[] { MscorlibRef },
syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) });
var csSource = @"
class Program
{
static void Main()
{
M.Goo(x => { });
}
}
";
var metadataStream = new MemoryStream();
var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true));
Assert.True(emitResult.Success);
var csProject = CreateCompilation(
Parse(csSource),
new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) });
Assert.Equal(0, csProject.GetDiagnostics().Count());
}
[Fact]
public void OverloadResolutionWithStaticTypeError()
{
var vbSource = @"
Imports System
Namespace Microsoft.VisualBasic.CompilerServices
<System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)>
Public NotInheritable Class StandardModuleAttribute
Inherits System.Attribute
Public Sub New()
MyBase.New()
End Sub
End Class
End Namespace
Public Module M
Public Dim F As Action(Of GC)
End Module
";
var vbProject = VisualBasic.VisualBasicCompilation.Create(
"VBProject",
references: new[] { MscorlibRef },
syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) });
var csSource = @"
class Program
{
static void Main()
{
M.F = x=>{};
}
}
";
var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true));
var csProject = CreateCompilation(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) });
csProject.VerifyDiagnostics(
// (6,15): error CS0721: 'GC': static types cannot be used as parameters
// M.F = x=>{};
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "x").WithArguments("System.GC").WithLocation(6, 15));
}
[WorkItem(540251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540251")]
[Fact]
public void AttributesCannotBeUsedInAnonymousMethods()
{
var csSource = @"
using System;
class Program
{
static void Main()
{
const string message = ""The parameter is obsolete"";
Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { };
}
}
";
var csProject = CreateCompilation(csSource);
csProject.VerifyEmitDiagnostics(
// (8,22): warning CS0219: The variable 'message' is assigned but its value is never used
// const string message = "The parameter is obsolete";
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "message").WithArguments("message").WithLocation(8, 22),
// (9,35): error CS7014: Attributes are not valid in this context.
// Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[ObsoleteAttribute(message)]").WithLocation(9, 35));
}
[WorkItem(540263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540263")]
[Fact]
public void ErrorsInUnboundLambdas()
{
var csSource = @"using System;
class Program
{
static void Main()
{
((Func<int>)delegate { return """"; })();
((Func<int>)delegate { })();
((Func<int>)delegate { 1 / 0; })();
}
}
";
CreateCompilation(csSource).VerifyDiagnostics(
// (7,39): error CS0029: Cannot implicitly convert type 'string' to 'int'
// ((Func<int>)delegate { return ""; })();
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(7, 39),
// (7,39): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// ((Func<int>)delegate { return ""; })();
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("anonymous method").WithLocation(7, 39),
// (8,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>'
// ((Func<int>)delegate { })();
Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(8, 21),
// (9,32): error CS0020: Division by constant zero
// ((Func<int>)delegate { 1 / 0; })();
Diagnostic(ErrorCode.ERR_IntDivByZero, "1 / 0").WithLocation(9, 32),
// (9,32): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((Func<int>)delegate { 1 / 0; })();
Diagnostic(ErrorCode.ERR_IllegalStatement, "1 / 0").WithLocation(9, 32),
// (9,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>'
// ((Func<int>)delegate { 1 / 0; })();
Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(9, 21)
);
}
[WorkItem(540181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540181")]
[Fact]
public void ErrorInLambdaArgumentList()
{
var csSource = @"using System;
class Program
{
public Program(string x) : this(() => x) { }
static void Main(string[] args)
{
((Action<string>)(f => Console.WriteLine(f)))(nulF);
}
}";
CreateCompilation(csSource).VerifyDiagnostics(
// (5,37): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
// public Program(string x) : this(() => x) { }
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => x").WithArguments("lambda expression", "string").WithLocation(5, 37),
// (8,55): error CS0103: The name 'nulF' does not exist in the current context
// ((Action<string>)(f => Console.WriteLine(f)))(nulF);
Diagnostic(ErrorCode.ERR_NameNotInContext, "nulF").WithArguments("nulF").WithLocation(8, 55));
}
[WorkItem(541725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541725")]
[Fact]
public void DelegateCreationIsNotStatement()
{
var csSource = @"
delegate void D();
class Program
{
public static void Main(string[] args)
{
D d = () => new D(() => { });
new D(()=>{});
}
}";
// Though it is legal to have an object-creation-expression, because it might be useful
// for its side effects, a delegate-creation-expression is not allowed as a
// statement expression.
CreateCompilation(csSource).VerifyDiagnostics(
// (7,21): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// D d = () => new D(() => { });
Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(() => { })"),
// (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// new D(()=>{});
Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(()=>{})"));
}
[WorkItem(542336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542336")]
[Fact]
public void ThisInStaticContext()
{
var csSource = @"
delegate void D();
class Program
{
public static void Main(string[] args)
{
D d = () => {
object o = this;
};
}
}";
CreateCompilation(csSource).VerifyDiagnostics(
// (8,24): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer
// object o = this;
Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")
);
}
[WorkItem(542431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542431")]
[Fact]
public void LambdaHasMoreParametersThanDelegate()
{
var csSource = @"
class C
{
static void Main()
{
System.Func<int> f = new System.Func<int>(r => 0);
}
}";
CreateCompilation(csSource).VerifyDiagnostics(
// (6,51): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments
Diagnostic(ErrorCode.ERR_BadDelArgCount, "r => 0").WithArguments("System.Func<int>", "1"));
}
[Fact, WorkItem(529054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529054")]
public void LambdaInDynamicCall()
{
var source = @"
public class Program
{
static void Main()
{
dynamic b = new string[] { ""AA"" };
bool exists = System.Array.Exists(b, o => o != ""BB"");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,46): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// bool exists = System.Array.Exists(b, o => o != "BB");
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, @"o => o != ""BB""")
);
}
[Fact, WorkItem(529389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529389")]
public void ParenthesizedLambdaInCastExpression()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int x = 1;
byte y = (byte) (x + x);
Func<int> f1 = (() => { return 1; });
Func<int> f2 = (Func<int>) (() => { return 2; });
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().
Where(e => e.Kind() == SyntaxKind.AddExpression).Single();
var tinfo = model.GetTypeInfo(expr);
var conv = model.GetConversion(expr);
// Not byte
Assert.Equal("int", tinfo.Type.ToDisplayString());
var exprs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>();
expr = exprs.First();
tinfo = model.GetTypeInfo(expr);
conv = model.GetConversion(expr);
Assert.True(conv.IsAnonymousFunction, "LambdaConversion");
Assert.Null(tinfo.Type);
var sym = model.GetSymbolInfo(expr).Symbol;
Assert.NotNull(sym);
Assert.Equal(SymbolKind.Method, sym.Kind);
Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind);
expr = exprs.Last();
tinfo = model.GetTypeInfo(expr);
conv = model.GetConversion(expr);
Assert.True(conv.IsAnonymousFunction, "LambdaConversion");
Assert.Null(tinfo.Type);
sym = model.GetSymbolInfo(expr).Symbol;
Assert.NotNull(sym);
Assert.Equal(SymbolKind.Method, sym.Kind);
Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind);
}
[WorkItem(544594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544594")]
[Fact]
public void LambdaInEnumMemberDecl()
{
var csSource = @"
public class TestClass
{
public enum Test { aa = ((System.Func<int>)(() => 1))() }
Test MyTest = Test.aa;
public static void Main()
{
}
}
";
CreateCompilation(csSource).VerifyDiagnostics(
// (4,29): error CS0133: The expression being assigned to 'TestClass.Test.aa' must be constant
Diagnostic(ErrorCode.ERR_NotConstantExpression, "((System.Func<int>)(() => 1))()").WithArguments("TestClass.Test.aa"),
// (5,10): warning CS0414: The field 'TestClass.MyTest' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "MyTest").WithArguments("TestClass.MyTest"));
}
[WorkItem(544932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544932")]
[Fact]
public void AnonymousLambdaInEnumSubtraction()
{
string source = @"
class Test
{
enum E1 : byte
{
A = byte.MinValue,
C = 1
}
static void Main()
{
int j = ((System.Func<Test.E1>)(() => E1.A))() - E1.C;
System.Console.WriteLine(j);
}
}
";
string expectedOutput = @"255";
CompileAndVerify(new[] { source }, expectedOutput: expectedOutput);
}
[WorkItem(545156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545156")]
[Fact]
public void SpeculativelyBindOverloadResolution()
{
string source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main()
{
Goo(() => () => { var x = (IEnumerable<int>)null; return x; });
}
static void Goo(Func<Func<IEnumerable>> x) { }
static void Goo(Func<Func<IFormattable>> x) { }
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single();
// Used to throw a NRE because of the ExpressionSyntax's null SyntaxTree.
model.GetSpeculativeSymbolInfo(
invocation.SpanStart,
SyntaxFactory.ParseExpression("Goo(() => () => { var x = null; return x; })"), // cast removed
SpeculativeBindingOption.BindAsExpression);
}
[WorkItem(545343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545343")]
[Fact]
public void LambdaUsingFieldInConstructor()
{
string source = @"
using System;
public class Derived
{
int field = 1;
Derived()
{
int local = 2;
// A lambda that captures a local and refers to an instance field.
Action a = () => Console.WriteLine(""Local = {0}, Field = {1}"", local, field);
// NullReferenceException if the ""this"" field of the display class hasn't been set.
a();
}
public static void Main()
{
Derived d = new Derived();
}
}";
CompileAndVerify(source, expectedOutput: "Local = 2, Field = 1");
}
[WorkItem(642222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642222")]
[Fact]
public void SpeculativelyBindOverloadResolutionAndInferenceWithError()
{
string source = @"
using System;using System.Linq.Expressions;
namespace IntellisenseBug
{
public class Program
{
void M(Mapper<FromData, ToData> mapper)
{
// Intellisense is broken here when you type . after the x:
mapper.Map(x => x/* */.
}
}
public class Mapper<TTypeFrom, TTypeTo>
{
public void Map<TPropertyFrom, TPropertyTo>(
Expression<Func<TTypeFrom, TPropertyFrom>> from,
Expression<Func<TTypeTo, TPropertyTo>> to)
{ }
}
public class FromData
{
public int Int { get; set; }
public string String { get; set; }
}
public class ToData
{
public int Id { get; set; }
public string Name
{
get; set;
}
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
// We don't actually require any particular diagnostics, but these are what we get.
compilation.VerifyDiagnostics(
// (10,36): error CS1001: Identifier expected
// mapper.Map(x => x/* */.
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (10,36): error CS1026: ) expected
// mapper.Map(x => x/* */.
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (10,36): error CS1002: ; expected
// mapper.Map(x => x/* */.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "")
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var xReference =
tree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType<ExpressionSyntax>()
.Where(e => e.ToFullString() == "x/* */")
.Last();
var typeInfo = model.GetTypeInfo(xReference);
Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("String"));
}
[WorkItem(722288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722288")]
[Fact]
public void CompletionInLambdaInIncompleteInvocation()
{
string source = @"
using System;
using System.Linq.Expressions;
public class SomeType
{
public string SomeProperty { get; set; }
}
public class IntelliSenseError
{
public static void Test1<T>(Expression<Func<T, object>> expr)
{
Console.WriteLine(((MemberExpression)expr.Body).Member.Name);
}
public static void Test2<T>(Expression<Func<T, object>> expr, bool additionalParameter)
{
Test1(expr);
}
public static void Main()
{
Test2<SomeType>(o => o/* */.
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
// We don't actually require any particular diagnostics, but these are what we get.
compilation.VerifyDiagnostics(
// (21,37): error CS1001: Identifier expected
// Test2<SomeType>(o => o/* */.
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (21,37): error CS1026: ) expected
// Test2<SomeType>(o => o/* */.
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (21,37): error CS1002: ; expected
// Test2<SomeType>(o => o/* */.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "")
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var oReference =
tree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType<NameSyntax>()
.Where(e => e.ToFullString() == "o/* */")
.Last();
var typeInfo = model.GetTypeInfo(oReference);
Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("SomeProperty"));
}
[WorkItem(871896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871896")]
[Fact]
public void Bug871896()
{
string source = @"
using System.Threading;
using System.Threading.Tasks;
class TestDataPointBase
{
private readonly IVisualStudioIntegrationService integrationService;
protected void TryGetDocumentId(CancellationToken token)
{
DocumentId documentId = null;
if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
{
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var oReference =
tree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType<ExpressionSyntax>()
.OrderByDescending(s => s.SpanStart);
foreach (var name in oReference)
{
CSharpExtensions.GetSymbolInfo(model, name);
}
// We should get a bunch of errors, but no asserts.
compilation.VerifyDiagnostics(
// (6,22): error CS0246: The type or namespace name 'IVisualStudioIntegrationService' could not be found (are you missing a using directive or an assembly reference?)
// private readonly IVisualStudioIntegrationService integrationService;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVisualStudioIntegrationService").WithArguments("IVisualStudioIntegrationService").WithLocation(6, 22),
// (9,9): error CS0246: The type or namespace name 'DocumentId' could not be found (are you missing a using directive or an assembly reference?)
// DocumentId documentId = null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "DocumentId").WithArguments("DocumentId").WithLocation(9, 9),
// (10,25): error CS0117: 'System.Threading.Tasks.Task' does not contain a definition for 'Run'
// if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
Diagnostic(ErrorCode.ERR_NoSuchMember, "Run").WithArguments("System.Threading.Tasks.Task", "Run").WithLocation(10, 25),
// (10,14): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)").WithLocation(10, 14),
// (6,54): warning CS0649: Field 'TestDataPointBase.integrationService' is never assigned to, and will always have its default value null
// private readonly IVisualStudioIntegrationService integrationService;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "integrationService").WithArguments("TestDataPointBase.integrationService", "null").WithLocation(6, 54)
);
}
[Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
public void Bug960755_01()
{
var source = @"
using System.Collections.Generic;
class C
{
static void M(IList<C> c)
{
var tmp = new C();
tmp.M((a, b) => c.Add);
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body;
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Null(symbolInfo.Symbol);
Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
}
[Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
public void Bug960755_02()
{
var source = @"
using System.Collections.Generic;
class C
{
static void M(IList<C> c)
{
int tmp = c.Add;
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer.Value;
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Null(symbolInfo.Symbol);
Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
}
[Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
public void Bug960755_03()
{
var source = @"
using System.Collections.Generic;
class C
{
static void M(IList<C> c)
{
var tmp = new C();
tmp.M((a, b) => c.Add);
}
static void M(System.Func<int, int, System.Action<C>> x)
{}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body;
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact]
public void RefLambdaInferenceMethodArgument()
{
var text = @"
delegate ref int D();
class C
{
static void MD(D d) { }
static int i = 0;
static void M()
{
MD(() => ref i);
MD(() => { return ref i; });
MD(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefLambdaInferenceDelegateCreation()
{
var text = @"
delegate ref int D();
class C
{
static int i = 0;
static void M()
{
var d = new D(() => ref i);
d = new D(() => { return ref i; });
d = new D(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefLambdaInferenceOverloadedDelegateType()
{
var text = @"
delegate ref int D();
delegate int E();
class C
{
static void M(D d) { }
static void M(E e) { }
static int i = 0;
static void M()
{
M(() => ref i);
M(() => { return ref i; });
M(delegate { return ref i; });
M(() => i);
M(() => { return i; });
M(delegate { return i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefLambdaInferenceArgumentBadRefReturn()
{
var text = @"
delegate int E();
class C
{
static void ME(E e) { }
static int i = 0;
static void M()
{
ME(() => ref i);
ME(() => { return ref i; });
ME(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (11,22): error CS8149: By-reference returns may only be used in by-reference returning methods.
// ME(() => ref i);
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(11, 22),
// (12,20): error CS8149: By-reference returns may only be used in by-reference returning methods.
// ME(() => { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(12, 20),
// (13,23): error CS8149: By-reference returns may only be used in by-reference returning methods.
// ME(delegate { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(13, 23));
}
[Fact]
public void RefLambdaInferenceDelegateCreationBadRefReturn()
{
var text = @"
delegate int E();
class C
{
static int i = 0;
static void M()
{
var e = new E(() => ref i);
e = new E(() => { return ref i; });
e = new E(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (9,33): error CS8149: By-reference returns may only be used in by-reference returning methods.
// var e = new E(() => ref i);
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(9, 33),
// (10,27): error CS8149: By-reference returns may only be used in by-reference returning methods.
// e = new E(() => { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(10, 27),
// (11,30): error CS8149: By-reference returns may only be used in by-reference returning methods.
// e = new E(delegate { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(11, 30));
}
[Fact]
public void RefLambdaInferenceMixedByValueAndByRefReturns()
{
var text = @"
delegate ref int D();
delegate int E();
class C
{
static void MD(D e) { }
static void ME(E e) { }
static int i = 0;
static void M()
{
MD(() => {
if (i == 0)
{
return ref i;
}
return i;
});
ME(() => {
if (i == 0)
{
return ref i;
}
return i;
});
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (18,13): error CS8150: By-value returns may only be used in by-value returning methods.
// return i;
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(18, 13),
// (23,17): error CS8149: By-reference returns may only be used in by-reference returning methods.
// return ref i;
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(23, 17));
}
[WorkItem(1112875, "DevDiv")]
[WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")]
[Fact]
public void Bug1112875_1()
{
var comp = CreateCompilation(@"
using System;
class Program
{
static void Main()
{
ICloneable c = """";
Goo(() => (c.Clone()), null);
}
static void Goo(Action x, string y) { }
static void Goo(Func<object> x, object y) { Console.WriteLine(42); }
}", options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")]
[Fact]
public void Bug1112875_2()
{
var comp = CreateCompilation(@"
class Program
{
void M()
{
var d = new System.Action(() => (new object()));
}
}
");
comp.VerifyDiagnostics(
// (6,41): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// var d = new System.Action(() => (new object()));
Diagnostic(ErrorCode.ERR_IllegalStatement, "(new object())").WithLocation(6, 41));
}
[WorkItem(1830, "https://github.com/dotnet/roslyn/issues/1830")]
[Fact]
public void FuncOfVoid()
{
var comp = CreateCompilation(@"
using System;
class Program
{
void M1<T>(Func<T> f) {}
void Main(string[] args)
{
M1(() => { return System.Console.Beep(); });
}
}
");
comp.VerifyDiagnostics(
// (8,27): error CS4029: Cannot return an expression of type 'void'
// M1(() => { return System.Console.Beep(); });
Diagnostic(ErrorCode.ERR_CantReturnVoid, "System.Console.Beep()").WithLocation(8, 27)
);
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_01()
{
var src = @"
using System;
class Program
{
static Func<Program, string> stuff()
{
return a => a.
}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,23): error CS1001: Identifier expected
// return a => a.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 23),
// (8,23): error CS1002: ; expected
// return a => a.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 23)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_02()
{
var src = @"
using System;
class Program
{
static void stuff()
{
Func<Program, string> l = a => a.
}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,42): error CS1001: Identifier expected
// Func<Program, string> l = a => a.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 42),
// (8,42): error CS1002: ; expected
// Func<Program, string> l = a => a.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 42)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_03()
{
var src = @"
using System;
class Program
{
static void stuff()
{
M1(a => a.);
}
static void M1(Func<Program, string> l){}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,20): error CS1001: Identifier expected
// M1(a => a.);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 20)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_04()
{
var src = @"
using System;
class Program
{
static void stuff()
{
var l = (Func<Program, string>) (a => a.);
}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,49): error CS1001: Identifier expected
// var l = (Func<Program, string>) (a => a.);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 49)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(3826, "https://github.com/dotnet/roslyn/issues/3826")]
public void ExpressionTreeSelfAssignmentShouldError()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int>> x = y => y = y;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (9,45): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// Expression<Func<int, int>> x = y => y = y;
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y = y").WithLocation(9, 45),
// (9,45): error CS0832: An expression tree may not contain an assignment operator
// Expression<Func<int, int>> x = y => y = y;
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "y = y").WithLocation(9, 45));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2(default(Struct1)));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2(default(Struct1)));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(Struct1)").WithArguments("Struct1").WithLocation(8, 40));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructDefaultExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2(default));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2(default));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 40));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructDefaultCastExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2((Struct1) default));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,50): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2((Struct1) default));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 50));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructNewExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2(new Struct1()));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2(new Struct1()));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "new Struct1()").WithArguments("Struct1").WithLocation(8, 40));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructParamExpressionTree()
{
var text = @"
using System.Linq.Expressions;
public delegate void Delegate1(Struct1 s);
public class Class1
{
public void Method1()
{
Method((Struct1 s) => Method2());
}
public void Method2() { }
public static void Method(Expression<Delegate1> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (9,25): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Struct1 s) => Method2());
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "s").WithArguments("Struct1").WithLocation(9, 25));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructParamLambda()
{
var text = @"
public delegate void Delegate1(Struct1 s);
public class Class1
{
public void Method1()
{
Method((Struct1 s) => Method2());
}
public void Method2() { }
public static void Method(Delegate1 expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics();
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void TypedReferenceExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method(() => Method2(default));
}
public void Method2(TypedReference tr) { }
public static void Method(Expression<Action> expression) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,30): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'.
// Method(() => Method2(default));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("TypedReference").WithLocation(8, 30));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void TypedReferenceParamExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public delegate void Delegate1(TypedReference tr);
public class Class1
{
public void Method1()
{
Method((TypedReference tr) => Method2());
}
public void Method2() { }
public static void Method(Expression<Delegate1> expression) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (9,32): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'.
// Method((TypedReference tr) => Method2());
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "tr").WithArguments("TypedReference").WithLocation(9, 32));
}
[Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")]
public void ReturnInferenceCache_Dynamic_vs_Object_01()
{
var source =
@"
using System;
using System.Collections;
using System.Collections.Generic;
public static class Program
{
public static void Main(string[] args)
{
IEnumerable<dynamic> dynX = null;
// CS1061 'object' does not contain a definition for 'Text'...
// tooltip on 'var' shows IColumn instead of IEnumerable<dynamic>
var result = dynX.Select(_ => _.Text);
}
public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector)
{
throw new NotImplementedException();
}
public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector)
{
System.Console.WriteLine(""Select<T, S>"");
return null;
}
}
public interface IColumn { }
";
var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: "Select<T, S>");
}
[Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")]
public void ReturnInferenceCache_Dynamic_vs_Object_02()
{
var source =
@"
using System;
using System.Collections;
using System.Collections.Generic;
public static class Program
{
public static void Main(string[] args)
{
IEnumerable<dynamic> dynX = null;
// CS1061 'object' does not contain a definition for 'Text'...
// tooltip on 'var' shows IColumn instead of IEnumerable<dynamic>
var result = dynX.Select(_ => _.Text);
}
public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector)
{
System.Console.WriteLine(""Select<T, S>"");
return null;
}
public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector)
{
throw new NotImplementedException();
}
}
public interface IColumn { }
";
var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: "Select<T, S>");
}
[Fact, WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void SyntaxAndSemanticErrorInLambda()
{
var source =
@"
using System;
class C
{
public static void Main(string[] args)
{
Action a = () => { new X().ToString() };
a();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,47): error CS1002: ; expected
// Action a = () => { new X().ToString() };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 47),
// (7,32): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)
// Action a = () => { new X().ToString() };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(7, 32)
);
}
[Fact, WorkItem(4527, "https://github.com/dotnet/roslyn/issues/4527")]
public void AnonymousMethodExpressionWithoutParameterList()
{
var source =
@"
using System;
using System.Threading.Tasks;
namespace RoslynAsyncDelegate
{
class Program
{
static EventHandler MyEvent;
static void Main(string[] args)
{
MyEvent += async delegate { await Task.Delay(0); };
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AnonymousMethodExpression)).Single();
Assert.Equal("async delegate { await Task.Delay(0); }", node1.ToString());
Assert.Equal("void System.EventHandler.Invoke(System.Object sender, System.EventArgs e)", model.GetTypeInfo(node1).ConvertedType.GetMembers("Invoke").Single().ToTestDisplayString());
var lambdaParameters = ((IMethodSymbol)(model.GetSymbolInfo(node1)).Symbol).Parameters;
Assert.Equal("System.Object <p0>", lambdaParameters[0].ToTestDisplayString());
Assert.Equal("System.EventArgs <p1>", lambdaParameters[1].ToTestDisplayString());
CompileAndVerify(compilation);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError01()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(() => { new Unbound1 }); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,58): error CS1526: A new expression requires (), [], or {} after type
// class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
Diagnostic(ErrorCode.ERR_BadNewExpr, "}").WithLocation(2, 58),
// (2,58): error CS1002: ; expected
// class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 58),
// (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?)
// class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError02()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,62): error CS1002: ; expected
// class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 62),
// (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?)
// class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError03()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,61): error CS1003: Syntax error, ',' expected
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_SyntaxError, "Unbound2").WithArguments(",", "").WithLocation(2, 61),
// (2,52): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52),
// (2,61): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 61),
// (2,42): error CS0103: The name 'Unbound1' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError04()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,52): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52),
// (2,42): error CS0103: The name 'Unbound1' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError05()
{
var source =
@"using System.Linq;
class C { C() { Unbound2.Select(x => Unbound1); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,17): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { Unbound2.Select(x => Unbound1); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 17),
// (2,38): error CS0103: The name 'Unbound1' does not exist in the current context
// class C { C() { Unbound2.Select(x => Unbound1); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 38)
);
}
[Fact]
[WorkItem(4480, "https://github.com/dotnet/roslyn/issues/4480")]
public void TestLambdaWithError06()
{
var source =
@"class Program
{
static void Main(string[] args)
{
// completion should work even in a syntactically invalid lambda
var handler = new MyDelegateType((s, e) => { e. });
}
}
public delegate void MyDelegateType(
object sender,
MyArgumentType e
);
public class MyArgumentType
{
public int SomePublicMember;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source)
.VerifyDiagnostics(
// var handler = new MyDelegateType((s, e) => { e. });
Diagnostic(ErrorCode.ERR_IdentifierExpected, "}").WithLocation(6, 57),
// (6,57): error CS1002: ; expected
// var handler = new MyDelegateType((s, e) => { e. });
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(6, 57)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("e", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal("MyArgumentType", typeInfo.Type.Name);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.NotEmpty(typeInfo.Type.GetMembers("SomePublicMember"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError07()
{
var source =
@"using System;
using System.Collections.Generic;
public static class Program
{
public static void Main()
{
var parameter = new List<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public static class Enumerable
{
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
return default(TSource);
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource defaultValue)
{
return default(TSource);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError08()
{
var source =
@"using System;
using System.Collections.Generic;
public static class Program
{
public static void Main()
{
var parameter = new List<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public static class Enumerable
{
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, params TSource[] defaultValue)
{
return default(TSource);
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, params TSource[] defaultValue)
{
return default(TSource);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError09()
{
var source =
@"using System;
public static class Program
{
public static void Main()
{
var parameter = new MyList<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public class MyList<TSource>
{
public TSource FirstOrDefault(TSource defaultValue)
{
return default(TSource);
}
public TSource FirstOrDefault(Func<TSource, bool> predicate, TSource defaultValue)
{
return default(TSource);
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (8,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError10()
{
var source =
@"using System;
public static class Program
{
public static void Main()
{
var parameter = new MyList<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public class MyList<TSource>
{
public TSource FirstOrDefault(params TSource[] defaultValue)
{
return default(TSource);
}
public TSource FirstOrDefault(Func<TSource, bool> predicate, params TSource[] defaultValue)
{
return default(TSource);
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (8,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(557, "https://github.com/dotnet/roslyn/issues/557")]
public void TestLambdaWithError11()
{
var source =
@"using System.Linq;
public static class Program
{
public static void Main()
{
var x = new {
X = """".Select(c => c.
Y = 0,
};
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("c", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Struct, typeInfo.Type.TypeKind);
Assert.Equal("Char", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("IsHighSurrogate")); // check it is the char we know and love
}
[Fact]
[WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")]
public void TestLambdaWithError12()
{
var source =
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
var z = args.Select(a => a.
var goo =
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("a", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
[Fact]
public void TestLambdaWithError13()
{
// These tests ensure we attempt to perform type inference and bind a lambda expression
// argument even when there are too many or too few arguments to an invocation, in the
// case when there is more than one method in the method group.
// See https://github.com/dotnet/roslyn/issues/11901 for the case of one method in the group
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Thing<string> t = null;
t.X1(x => x, 1); // too many args
t.X2(x => x); // too few args
t.M2(string.Empty, x => x, 1); // too many args
t.M3(string.Empty, x => x); // too few args
}
}
public class Thing<T>
{
public void M2<T>(T x, Func<T, T> func) {}
public void M3<T>(T x, Func<T, T> func, T y) {}
// Ensure we have more than one method in the method group
public void M2() {}
public void M3() {}
}
public static class XThing
{
public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
// Ensure we have more than one method in the method group
public static void X1(this object self) {}
public static void X2(this object self) {}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")]
public void TestLambdaWithError15()
{
// These tests ensure we attempt to perform type inference and bind a lambda expression
// argument even when there are too many or too few arguments to an invocation, in the
// case when there is exactly one method in the method group.
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Thing<string> t = null;
t.X1(x => x, 1); // too many args
t.X2(x => x); // too few args
t.M2(string.Empty, x => x, 1); // too many args
t.M3(string.Empty, x => x); // too few args
}
}
public class Thing<T>
{
public void M2<T>(T x, Func<T, T> func) {}
public void M3<T>(T x, Func<T, T> func, T y) {}
}
public static class XThing
{
public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")]
public void TestLambdaWithError16()
{
// These tests ensure we use the substituted method to bind a lambda expression
// argument even when there are too many or too few arguments to an invocation, in the
// case when there is exactly one method in the method group.
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Thing<string> t = null;
t.X1<string>(x => x, 1); // too many args
t.X2<string>(x => x); // too few args
t.M2<string>(string.Empty, x => x, 1); // too many args
t.M3<string>(string.Empty, x => x); // too few args
}
}
public class Thing<T>
{
public void M2<T>(T x, Func<T, T> func) {}
public void M3<T>(T x, Func<T, T> func, T y) {}
}
public static class XThing
{
public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
public void TestLambdaWithError17()
{
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Ma(action: (x, y) => x.ToString(), t: string.Empty);
Mb(action: (x, y) => x.ToString(), t: string.Empty);
}
static void Ma<T>(T t, Action<T, T, int> action) { }
static void Mb<T>(T t, Action<T, T, int> action) { }
static void Mb() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
public void TestLambdaWithError18()
{
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Ma(string.Empty, (x, y) => x.ToString());
Mb(string.Empty, (x, y) => x.ToString());
}
static void Ma<T>(T t, Action<T, T, int> action) { }
static void Mb<T>(T t, Action<T, T, int> action) { }
static void Mb() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
public void TestLambdaWithError19()
{
var source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
Ma(string.Empty, (x, y) => x.ToString());
Mb(string.Empty, (x, y) => x.ToString());
Mc(string.Empty, (x, y) => x.ToString());
}
static void Ma<T>(T t, Expression<Action<T, T, int>> action) { }
static void Mb<T>(T t, Expression<Action<T, T, int>> action) { }
static void Mb<T>(T t, Action<T, T, int> action) { }
static void Mc<T>(T t, Expression<Action<T, T, int>> action) { }
static void Mc() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
// See MaxParameterListsForErrorRecovery.
[Fact]
public void BuildArgumentsForErrorRecovery_ManyOverloads()
{
BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery - 1, tooMany: false);
BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery, tooMany: true);
}
private void BuildArgumentsForErrorRecovery_ManyOverloads_Internal(int n, bool tooMany)
{
var builder = new StringBuilder();
builder.AppendLine("using System;");
for (int i = 0; i < n; i++)
{
builder.AppendLine($"class C{i} {{ }}");
}
builder.Append(
@"class A { }
class B { }
class C
{
void M()
{
F(1, (t, a, b, c) => { });
var o = this[(a, b, c) => { }];
}
");
// Too few parameters.
AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, C{i}> a) {{ }}");
AppendLines(builder, n, i => $" object this[Action<A, C{i}> a] => {i}");
// Type inference failure.
AppendLines(builder, n, i => $" void F<T, U>(T t, Action<T, U, C{i}> a) where U : T {{ }}");
// Too many parameters.
AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, B, C, C{i}> a) {{ }}");
AppendLines(builder, n, i => $" object this[Action<A, B, C, C{i}> a] => {i}");
builder.AppendLine("}");
var source = builder.ToString();
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambdas = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().ToArray();
// F(1, (t, a, b, c) => { });
var lambda = lambdas[0];
var parameters = lambda.ParameterList.Parameters;
var parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]);
Assert.False(parameter.Type.IsErrorType());
Assert.Equal("System.Int32 t", parameter.ToTestDisplayString());
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[1]);
Assert.False(parameter.Type.IsErrorType());
Assert.Equal("A a", parameter.ToTestDisplayString());
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[3]);
Assert.Equal(tooMany, parameter.Type.IsErrorType());
Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString());
// var o = this[(a, b, c) => { }];
lambda = lambdas[1];
parameters = lambda.ParameterList.Parameters;
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]);
Assert.False(parameter.Type.IsErrorType());
Assert.Equal("A a", parameter.ToTestDisplayString());
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[2]);
Assert.Equal(tooMany, parameter.Type.IsErrorType());
Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString());
}
private static void AppendLines(StringBuilder builder, int n, Func<int, string> getLine)
{
for (int i = 0; i < n; i++)
{
builder.AppendLine(getLine(i));
}
}
[Fact]
[WorkItem(13797, "https://github.com/dotnet/roslyn/issues/13797")]
public void DelegateAsAction()
{
var source = @"
using System;
public static class C
{
public static void M() => Dispatch(delegate { });
public static T Dispatch<T>(Func<T> func) => default(T);
public static void Dispatch(Action func) { }
}";
var comp = CreateCompilation(source);
CompileAndVerify(comp);
}
[Fact, WorkItem(278481, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=278481")]
public void LambdaReturningNull_1()
{
var src = @"
public static class ExtensionMethods
{
public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Linq.IQueryable<TOuter> outerValues,
System.Linq.IQueryable<TInner> innerValues,
System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector,
System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector,
System.Collections.Generic.IEqualityComparer<TKey> comparer)
{ return null; }
public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Linq.IQueryable<TOuter> outerValues,
System.Linq.IQueryable<TInner> innerValues,
System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector,
System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector)
{
System.Console.WriteLine(""1"");
return null;
}
public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Collections.Generic.IEnumerable<TOuter> outerValues,
System.Linq.IQueryable<TInner> innerValues,
System.Func<TOuter, TKey> outerKeySelector,
System.Func<TInner, TKey> innerKeySelector,
System.Func<TOuter, TInner, TResult> fullResultSelector,
System.Func<TOuter, TResult> partialResultSelector)
{
System.Console.WriteLine(""2"");
return null;
}
public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Collections.Generic.IEnumerable<TOuter> outerQueryable,
System.Collections.Generic.IEnumerable<TInner> innerQueryable,
System.Func<TOuter, TKey> outerKeySelector,
System.Func<TInner, TKey> innerKeySelector,
System.Func<TOuter, TInner, TResult> resultSelector)
{ return null; }
}
partial class C
{
public static void Main()
{
System.Linq.IQueryable<A> outerValue = null;
System.Linq.IQueryable<B> innerValues = null;
outerValue.LeftOuterJoin(innerValues,
co => co.id,
coa => coa.id,
(co, coa) => null,
co => co);
}
}
class A
{
public int id=2;
}
class B
{
public int id = 2;
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1");
}
[Fact, WorkItem(296550, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296550")]
public void LambdaReturningNull_2()
{
var src = @"
class Test1<T>
{
public void M1(System.Func<T> x) {}
public void M1<S>(System.Func<S> x) {}
public void M2<S>(System.Func<S> x) {}
public void M2(System.Func<T> x) {}
}
class Test2 : Test1<System.>
{
void Main()
{
M1(()=> null);
M2(()=> null);
}
}
";
var comp = CreateCompilation(src, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (10,32): error CS1001: Identifier expected
// class Test2 : Test1<System.>
Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(10, 32)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void LambdaSquigglesArea()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Action<bool>> x = x1 => x2 =>
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,58): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// System.Func<bool, System.Action<bool>> x = x1 => x2 =>
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x2 =>").WithArguments("lambda expression").WithLocation(6, 58)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void LambdaSquigglesAreaInAsync()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,93): error CS4010: Cannot convert async lambda expression to delegate type 'Task<Action<bool>>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Task<Action<bool>>'.
// System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
Diagnostic(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, "x2 =>").WithArguments("lambda expression", "System.Threading.Tasks.Task<System.Action<bool>>").WithLocation(6, 93),
// (6,90): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 90)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void DelegateSquigglesArea()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2)
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,58): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2)
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate(bool x2)").WithArguments("lambda expression").WithLocation(6, 58)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void DelegateWithoutArgumentsSquigglesArea()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Action> x = x1 => delegate
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,52): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// System.Func<bool, System.Action> x = x1 => delegate
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate").WithArguments("lambda expression").WithLocation(6, 52)
);
}
[Fact]
public void ThrowExpression_Lambda()
{
var src = @"using System;
class C
{
public static void Main()
{
Action a = () => throw new Exception(""1"");
try
{
a();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Func<int, int> b = x => throw new Exception(""2"");
try
{
b(0);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
b = (int x) => throw new Exception(""3"");
try
{
b(0);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
b = (x) => throw new Exception(""4"");
try
{
b(0);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1234");
}
[Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
public void InMalformedEmbeddedStatement_01()
{
var source = @"
class Program
{
void method1()
{
if (method2())
.Any(b => b.ContentType, out var chars)
{
}
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single();
var model = comp.GetSemanticModel(tree);
Assert.Equal("ContentType", contentType.ToString());
Assert.Null(model.GetSymbolInfo(contentType).Symbol);
Assert.Equal(TypeKind.Error, model.GetTypeInfo(contentType).Type.TypeKind);
ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single();
model = comp.GetSemanticModel(tree);
Assert.Equal("b", b.ToString());
ISymbol symbol = model.GetSymbolInfo(b).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.Equal("? b", symbol.ToTestDisplayString());
Assert.Equal(TypeKind.Error, model.GetTypeInfo(b).Type.TypeKind);
ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
model = comp.GetSemanticModel(tree);
symbol = model.GetDeclaredSymbol(parameterSyntax);
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.Equal("? b", symbol.ToTestDisplayString());
}
[Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
public void InMalformedEmbeddedStatement_02()
{
var source = @"
class Program
{
void method1()
{
if (method2())
.Any(b => b.ContentType, out var chars)
{
}
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single();
var model = comp.GetSemanticModel(tree);
Assert.Equal("ContentType", contentType.ToString());
var lambda = (IMethodSymbol)model.GetEnclosingSymbol(contentType.SpanStart);
Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind);
ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single();
model = comp.GetSemanticModel(tree);
Assert.Equal("b", b.ToString());
lambda = (IMethodSymbol)model.GetEnclosingSymbol(b.SpanStart);
Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind);
model = comp.GetSemanticModel(tree);
ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
Assert.Equal("void Program.method1()", model.GetEnclosingSymbol(parameterSyntax.SpanStart).ToTestDisplayString());
}
[Fact]
public void ShadowNames_Local()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M()
{
Action a1 = () => { object x = 0; }; // local
Action<string> a2 = x => { }; // parameter
Action<string> a3 = (string x) => { }; // parameter
object x = null;
Action a4 = () => { void x() { } }; // method
Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = () => { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36),
// (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = x => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29),
// (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a3 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
// (13,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a4 = () => { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(13, 34),
// (14,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(14, 38));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Parameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static Action<object> F = (object x) =>
{
Action a1 = () => { object x = 0; }; // local
Action<string> a2 = x => { }; // parameter
Action<string> a3 = (string x) => { }; // parameter
Action a4 = () => { void x() { } }; // method
Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
};
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = () => { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36),
// (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = x => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29),
// (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a3 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
// (13,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 38));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_TypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M<x>()
{
Action a1 = () => { object x = 0; }; // local
Action<string> a2 = x => { }; // parameter
Action<string> a3 = (string x) => { }; // parameter
Action a4 = () => { void x() { } }; // method
Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,36): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a1 = () => { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 36),
// (10,29): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> a2 = x => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 29),
// (11,37): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> a3 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 37),
// (12,34): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a4 = () => { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(12, 34),
// (13,38): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
// Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(13, 38));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_QueryParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
_ = from x in args select (Action)(() => { object x = 0; }); // local
_ = from x in args select (Action<string>)(x => { }); // parameter
_ = from x in args select (Action<string>)((string x) => { }); // parameter
_ = from x in args select (Action)(() => { void x() { } }); // method
_ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,59): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// _ = from x in args select (Action)(() => { object x = 0; }); // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 59),
// (10,52): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// _ = from x in args select (Action<string>)(x => { }); // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 52),
// (11,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// _ = from x in args select (Action<string>)((string x) => { }); // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 60),
// (13,61): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 61));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Local_Delegate()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M()
{
object x = null;
Action a1 = delegate() { object x = 0; }; // local
Action<string> a2 = delegate(string x) { }; // parameter
Action a3 = delegate() { void x() { } }; // method
Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (10,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = delegate() { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 41),
// (11,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = delegate(string x) { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 45),
// (12,39): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a3 = delegate() { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 39),
// (13,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 43));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Parameter_Delegate()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static Action<object> F = (object x) =>
{
Action a1 = delegate() { object x = 0; }; // local
Action<string> a2 = delegate(string x) { }; // parameter
Action a3 = delegate() { void x() { } }; // method
Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
};
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = delegate() { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 41),
// (10,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = delegate(string x) { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 45),
// (12,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 43));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_TypeParameter_Delegate()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M<x>()
{
Action a1 = delegate() { object x = 0; }; // local
Action<string> a2 = delegate(string x) { }; // parameter
Action a3 = delegate() { void x() { } }; // method
Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,41): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a1 = delegate() { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 41),
// (10,45): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> a2 = delegate(string x) { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 45),
// (11,39): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a3 = delegate() { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 39),
// (12,43): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
// Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 43));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LambdaInsideLambda()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M<T>(object x)
{
Action a1 = () =>
{
Action b1 = () => { object x = 1; }; // local
Action<string> b2 = (string x) => { }; // parameter
};
Action a2 = () =>
{
Action b3 = () => { object T = 3; }; // local
Action<string> b4 = T => { }; // parameter
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (10,40): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action b1 = () => { object x = 1; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 40),
// (11,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> b2 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 41),
// (15,40): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action b3 = () => { object T = 3; }; // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 40),
// (16,33): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> b4 = T => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(16, 33));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Underscore_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, Func<int, int>> f = _ => _ => _;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,44): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, Func<int, int>> f = _ => _ => _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 44));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Underscore_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, int, int> f = (_, _) => 0;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,37): error CS8370: Feature 'lambda discard parameters' is not available in C# 7.3. Please use language version 9.0 or greater.
// Func<int, int, int> f = (_, _) => 0;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "_").WithArguments("lambda discard parameters", "9.0").WithLocation(8, 37));
comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ShadowNames_Nested_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,55): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 55),
// (8,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 60));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Nested_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,87): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 87),
// (8,94): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(8, 94),
// (8,97): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 97));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LambdaInsideLocalFunction_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
void F1()
{
object x = null;
Action a1 = () => { int x = 0; };
}
void F2<T>()
{
Action a2 = () => { int T = 0; };
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = () => { int x = 0; };
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
// (15,37): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a2 = () => { int T = 0; };
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 37));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LambdaInsideLocalFunction_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M<T>()
{
object x = null;
void F()
{
Action<int> a1 = (int x) =>
{
Action b1 = () => { int T = 0; };
};
Action a2 = () =>
{
int x = 0;
Action<int> b2 = (int T) => { };
};
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (11,35): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<int> a1 = (int x) =>
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 35),
// (13,41): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action b1 = () => { int T = 0; };
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(13, 41),
// (17,21): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x = 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(17, 21),
// (18,39): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<int> b2 = (int T) => { };
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(18, 39));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaAttributes_01()
{
var sourceA =
@"using System;
class A : Attribute { }
class B : Attribute { }
partial class Program
{
static Delegate D1() => (Action)([A] () => { });
static Delegate D2(int x) => (Func<int, int, int>)((int y, [A][B] int z) => x);
static Delegate D3() => (Action<int, object>)(([A]_, y) => { });
Delegate D4() => (Func<int>)([return: A][B] () => GetHashCode());
}";
var sourceB =
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
partial class Program
{
static string GetAttributeString(object a)
{
return a.GetType().FullName;
}
static void Report(Delegate d)
{
var m = d.Method;
var forMethod = ToString(""method"", m.GetCustomAttributes(inherit: false));
var forReturn = ToString(""return"", m.ReturnTypeCustomAttributes.GetCustomAttributes(inherit: false));
var forParameters = ToString(""parameter"", m.GetParameters().SelectMany(p => p.GetCustomAttributes(inherit: false)));
Console.WriteLine(""{0}:{1}{2}{3}"", m.Name, forMethod, forReturn, forParameters);
}
static string ToString(string target, IEnumerable<object> attributes)
{
var builder = new StringBuilder();
foreach (var attribute in attributes)
builder.Append($"" [{target}: {attribute}]"");
return builder.ToString();
}
static void Main()
{
Report(D1());
Report(D2(0));
Report(D3());
Report(new Program().D4());
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseExe);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>();
var pairs = exprs.Select(e => (e, model.GetSymbolInfo(e).Symbol)).ToArray();
var expectedAttributes = new[]
{
"[A] () => { }: [method: A]",
"(int y, [A][B] int z) => x: [parameter: A] [parameter: B]",
"([A]_, y) => { }: [parameter: A]",
"[return: A][B] () => GetHashCode(): [method: B] [return: A]",
};
AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesInternal(p.Item1, p.Item2)));
AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesPublic(p.Item1, p.Item2)));
CompileAndVerify(comp, expectedOutput:
@"<D1>b__0_0: [method: A]
<D2>b__0: [parameter: A] [parameter: B]
<D3>b__2_0: [parameter: A]
<D4>b__3_0: [method: System.Runtime.CompilerServices.CompilerGeneratedAttribute] [method: B] [return: A]");
static string getAttributesInternal(LambdaExpressionSyntax expr, ISymbol symbol)
{
var method = symbol.GetSymbol<MethodSymbol>();
return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes()));
}
static string getAttributesPublic(LambdaExpressionSyntax expr, ISymbol symbol)
{
var method = (IMethodSymbol)symbol;
return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes()));
}
static string format(LambdaExpressionSyntax expr, IEnumerable<object> methodAttributes, IEnumerable<object> returnAttributes, IEnumerable<object> parameterAttributes)
{
var forMethod = toString("method", methodAttributes);
var forReturn = toString("return", returnAttributes);
var forParameters = toString("parameter", parameterAttributes);
return $"{expr}:{forMethod}{forReturn}{forParameters}";
}
static string toString(string target, IEnumerable<object> attributes)
{
var builder = new StringBuilder();
foreach (var attribute in attributes)
builder.Append($" [{target}: {attribute}]");
return builder.ToString();
}
}
[Fact]
public void LambdaAttributes_02()
{
var source =
@"using System;
class AAttribute : Attribute { }
class BAttribute : Attribute { }
class C
{
static void Main()
{
Action<object, object> a;
a = [A, B] (x, y) => { };
a = ([A] x, [B] y) => { };
a = (object x, [A][B] object y) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,13): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = [A, B] (x, y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A, B]").WithArguments("lambda attributes", "10.0").WithLocation(9, 13),
// (10,14): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = ([A] x, [B] y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(10, 14),
// (10,21): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = ([A] x, [B] y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(10, 21),
// (11,24): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = (object x, [A][B] object y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(11, 24),
// (11,27): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = (object x, [A][B] object y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(11, 27));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaAttributes_03()
{
var source =
@"using System;
class AAttribute : Attribute { }
class BAttribute : Attribute { }
class C
{
static void Main()
{
Action<object, object> a = delegate (object x, [A][B] object y) { };
Func<object, object> f = [A][B] x => x;
}
}";
var expectedDiagnostics = new[]
{
// (8,56): error CS7014: Attributes are not valid in this context.
// Action<object, object> a = delegate (object x, [A][B] object y) { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 56),
// (8,59): error CS7014: Attributes are not valid in this context.
// Action<object, object> a = delegate (object x, [A][B] object y) { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[B]").WithLocation(8, 59),
// (9,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list.
// Func<object, object> f = [A][B] x => x;
Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[A]").WithLocation(9, 34),
// (9,37): error CS8916: Attributes on lambda expressions require a parenthesized parameter list.
// Func<object, object> f = [A][B] x => x;
Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[B]").WithLocation(9, 37)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(expectedDiagnostics);
}
[Fact]
public void LambdaAttributes_04()
{
var sourceA =
@"namespace N1
{
class A1Attribute : System.Attribute { }
}
namespace N2
{
class A2Attribute : System.Attribute { }
}";
var sourceB =
@"using N1;
using N2;
class Program
{
static void Main()
{
System.Action a1 = [A1] () => { };
System.Action<object> a2 = ([A2] object obj) => { };
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaAttributes_05()
{
var source =
@"class Program
{
static void Main()
{
System.Action a1 = [A1] () => { };
System.Func<object> a2 = [return: A2] () => null;
System.Action<object> a3 = ([A3] object obj) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,29): error CS0246: The type or namespace name 'A1Attribute' could not be found (are you missing a using directive or an assembly reference?)
// System.Action a1 = [A1] () => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1Attribute").WithLocation(5, 29),
// (5,29): error CS0246: The type or namespace name 'A1' could not be found (are you missing a using directive or an assembly reference?)
// System.Action a1 = [A1] () => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1").WithLocation(5, 29),
// (6,43): error CS0246: The type or namespace name 'A2Attribute' could not be found (are you missing a using directive or an assembly reference?)
// System.Func<object> a2 = [return: A2] () => null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2Attribute").WithLocation(6, 43),
// (6,43): error CS0246: The type or namespace name 'A2' could not be found (are you missing a using directive or an assembly reference?)
// System.Func<object> a2 = [return: A2] () => null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2").WithLocation(6, 43),
// (7,38): error CS0246: The type or namespace name 'A3Attribute' could not be found (are you missing a using directive or an assembly reference?)
// System.Action<object> a3 = ([A3] object obj) => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3Attribute").WithLocation(7, 38),
// (7,38): error CS0246: The type or namespace name 'A3' could not be found (are you missing a using directive or an assembly reference?)
// System.Action<object> a3 = ([A3] object obj) => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3").WithLocation(7, 38));
}
[Fact]
public void LambdaAttributes_06()
{
var source =
@"using System;
class AAttribute : Attribute
{
public AAttribute(Action a) { }
}
[A([B] () => { })]
class BAttribute : Attribute
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,2): error CS0181: Attribute constructor parameter 'a' has type 'Action', which is not a valid attribute parameter type
// [A([B] () => { })]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "System.Action").WithLocation(6, 2));
}
[Fact]
public void LambdaAttributes_BadAttributeLocation()
{
var source =
@"using System;
[AttributeUsage(AttributeTargets.Property)]
class PropAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
class MethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.ReturnValue)]
class ReturnAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
class ParamAttribute : Attribute { }
[AttributeUsage(AttributeTargets.GenericParameter)]
class TypeParamAttribute : Attribute { }
class Program
{
static void Main()
{
Action<object> a =
[Prop] // 1
[Return] // 2
[Method]
[return: Prop] // 3
[return: Return]
[return: Method] // 4
(
[Param]
[TypeParam] // 5
object o) =>
{
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (23,14): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [Prop] // 1
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(23, 14),
// (24,14): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations.
// [Return] // 2
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(24, 14),
// (26,22): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [return: Prop] // 3
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(26, 22),
// (28,22): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations.
// [return: Method] // 4
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(28, 22),
// (31,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations.
// [TypeParam] // 5
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(31, 14));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var symbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol;
Assert.NotNull(symbol);
verifyAttributes(symbol.GetAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute");
verifyAttributes(symbol.GetReturnTypeAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute");
verifyAttributes(symbol.Parameters[0].GetAttributes(), "ParamAttribute", "TypeParamAttribute");
void verifyAttributes(ImmutableArray<AttributeData> attributes, params string[] expectedAttributeNames)
{
var actualAttributes = attributes.SelectAsArray(a => a.AttributeClass.GetSymbol());
var expectedAttributes = expectedAttributeNames.Select(n => comp.GetTypeByMetadataName(n));
AssertEx.Equal(expectedAttributes, actualAttributes);
}
}
[Fact]
public void LambdaAttributes_AttributeSemanticModel()
{
var source =
@"using System;
class AAttribute : Attribute { }
class BAttribute : Attribute { }
class CAttribute : Attribute { }
class DAttribute : Attribute { }
class Program
{
static void Main()
{
Action a = [A] () => { };
Func<object> b = [return: B] () => null;
Action<object> c = ([C] object obj) => { };
Func<object, object> d = [D] x => x;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (13,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list.
// Func<object, object> d = [D] x => x;
Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[D]").WithLocation(13, 34));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>();
var actualAttributes = attributeSyntaxes.Select(a => model.GetSymbolInfo(a).Symbol.GetSymbol<MethodSymbol>()).ToImmutableArray();
var expectedAttributes = new[] { "AAttribute", "BAttribute", "CAttribute", "DAttribute" }.Select(a => comp.GetTypeByMetadataName(a).InstanceConstructors.Single()).ToImmutableArray();
AssertEx.Equal(expectedAttributes, actualAttributes);
}
[Theory]
[InlineData("Action a = [A] () => { };")]
[InlineData("Func<object> f = [return: A] () => null;")]
[InlineData("Action<int> a = ([A] int i) => { };")]
public void LambdaAttributes_SpeculativeSemanticModel(string statement)
{
string source =
$@"using System;
class AAttribute : Attribute {{ }}
class Program
{{
static void Main()
{{
{statement}
}}
}}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var a = (IdentifierNameSyntax)tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name;
Assert.Equal("A", a.Identifier.Text);
var attrInfo = model.GetSymbolInfo(a);
var attrType = comp.GetMember<NamedTypeSymbol>("AAttribute").GetPublicSymbol();
var attrCtor = attrType.GetMember(".ctor");
Assert.Equal(attrCtor, attrInfo.Symbol);
// Assert that this is also true for the speculative semantic model
var newTree = SyntaxFactory.ParseSyntaxTree(source + " ");
var m = newTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model));
a = (IdentifierNameSyntax)newTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name;
Assert.Equal("A", a.Identifier.Text);
// If we aren't using the right binder here, the compiler crashes going through the binder factory
var info = model.GetSymbolInfo(a);
// This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135
Assert.Equal(attrType, info.Symbol);
}
[Fact]
public void LambdaAttributes_DisallowedAttributes()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : Attribute { }
public class IsUnmanagedAttribute : Attribute { }
public class IsByRefLikeAttribute : Attribute { }
public class NullableContextAttribute : Attribute { public NullableContextAttribute(byte b) { } }
}
class Program
{
static void Main()
{
Action a =
[IsReadOnly] // 1
[IsUnmanaged] // 2
[IsByRefLike] // 3
[Extension] // 4
[NullableContext(0)] // 5
() => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (15,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly] // 1
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(15, 14),
// (16,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage.
// [IsUnmanaged] // 2
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(16, 14),
// (17,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage.
// [IsByRefLike] // 3
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(17, 14),
// (18,14): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.
// [Extension] // 4
Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(18, 14),
// (19,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [NullableContext(0)] // 5
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(19, 14));
}
[Fact]
public void LambdaAttributes_DisallowedSecurityAttributes()
{
var source =
@"using System;
using System.Security;
class Program
{
static void Main()
{
Action a =
[SecurityCritical] // 1
[SecuritySafeCriticalAttribute] // 2
async () => { }; // 3
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,14): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method.
// [SecurityCritical] // 1
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(8, 14),
// (9,14): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method.
// [SecuritySafeCriticalAttribute] // 2
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(9, 14),
// (10,22): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async () => { }; // 3
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(10, 22));
}
[Fact]
public void LambdaAttributes_ObsoleteAttribute()
{
var source =
@"using System;
class Program
{
static void Report(Action a)
{
foreach (var attribute in a.Method.GetCustomAttributes(inherit: false))
Console.Write(attribute);
}
static void Main()
{
Report([Obsolete] () => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "System.ObsoleteAttribute");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal("System.ObsoleteAttribute", symbol.GetAttributes().Single().ToString());
}
[Fact]
public void LambdaParameterAttributes_Conditional()
{
var source =
@"using System;
using System.Diagnostics;
class Program
{
static void Report(Action a)
{
}
static void Main()
{
Report([Conditional(""DEBUG"")] static () => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (10,17): error CS0577: The Conditional attribute is not valid on 'lambda expression' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation
// Report([Conditional("DEBUG")] static () => { });
Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional(""DEBUG"")").WithArguments("lambda expression").WithLocation(10, 17));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single();
Assert.Equal(new[] { "DEBUG" }, lambda.GetAppliedConditionalSymbols());
}
[Fact]
public void LambdaAttributes_WellKnownAttributes()
{
var sourceA =
@"using System;
using System.Runtime.InteropServices;
using System.Security;
class Program
{
static void Main()
{
Action a1 = [DllImport(""MyModule.dll"")] static () => { };
Action a2 = [DynamicSecurityMethod] () => { };
Action a3 = [SuppressUnmanagedCodeSecurity] () => { };
Func<object> a4 = [return: MarshalAs((short)0)] () => null;
}
}";
var sourceB =
@"namespace System.Security
{
internal class DynamicSecurityMethodAttribute : Attribute { }
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,22): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// Action a1 = [DllImport("MyModule.dll")] static () => { };
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(8, 22));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(4, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Null(lambdas[0].GetDllImportData()); // [DllImport] is ignored if there are errors.
Assert.True(lambdas[1].RequiresSecurityObject);
Assert.True(lambdas[2].HasDeclarativeSecurity);
Assert.Equal(default, lambdas[3].ReturnValueMarshallingInformation.UnmanagedType);
}
[Fact]
public void LambdaAttributes_Permissions()
{
var source =
@"#pragma warning disable 618
using System;
using System.Security.Permissions;
class Program
{
static void Main()
{
Action a1 = [PermissionSet(SecurityAction.Deny)] () => { };
}
}";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single();
Assert.NotEmpty(lambda.GetSecurityInformation());
}
[Fact]
public void LambdaAttributes_NullableAttributes_01()
{
var source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Func<object> a1 = [return: MaybeNull][return: NotNull] () => null;
Func<object, object> a2 = [return: NotNullIfNotNull(""obj"")] (object obj) => obj;
Func<bool> a4 = [MemberNotNull(""x"")][MemberNotNullWhen(false, ""y"")][MemberNotNullWhen(true, ""z"")] () => true;
}
}";
var comp = CreateCompilation(
new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition, NotNullIfNotNullAttributeDefinition, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition },
parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(3, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Equal(FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull, lambdas[0].ReturnTypeFlowAnalysisAnnotations);
Assert.Equal(new[] { "obj" }, lambdas[1].ReturnNotNullIfParameterNotNull);
Assert.Equal(new[] { "x" }, lambdas[2].NotNullMembers);
Assert.Equal(new[] { "y" }, lambdas[2].NotNullWhenFalseMembers);
Assert.Equal(new[] { "z" }, lambdas[2].NotNullWhenTrueMembers);
}
[Fact]
public void LambdaAttributes_NullableAttributes_02()
{
var source =
@"#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Func<object> a1 = [return: MaybeNull] () => null;
Func<object?> a2 = [return: NotNull] () => null;
}
}";
var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Report WRN_NullReferenceReturn for a2, not for a1.
comp.VerifyDiagnostics(
// (8,53): warning CS8603: Possible null reference return.
// Func<object> a1 = [return: MaybeNull] () => null;
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 53));
}
[Fact]
public void LambdaAttributes_NullableAttributes_03()
{
var source =
@"#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Action<object> a1 = ([AllowNull] x) => { x.ToString(); };
Action<object?> a2 = ([DisallowNull] x) => { x.ToString(); };
}
}";
var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Report nullability mismatch warning assigning lambda to a2.
comp.VerifyDiagnostics(
// (8,50): warning CS8602: Dereference of a possibly null reference.
// Action<object> a1 = ([AllowNull] x) => { x.ToString(); };
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 50));
}
[WorkItem(55013, "https://github.com/dotnet/roslyn/issues/55013")]
[Fact]
public void NullableTypeArraySwitchPattern()
{
var source =
@"#nullable enable
class C
{
object? field;
string Prop => field switch
{
string?[] a => ""a""
};
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,13): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null
// object? field;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 13),
// (5,26): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// string Prop => field switch
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 26));
}
[Fact]
public void LambdaAttributes_DoesNotReturn()
{
var source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Action a1 = [DoesNotReturn] () => { };
Action a2 = [DoesNotReturn] () => throw new Exception();
}
}";
var comp = CreateCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Report warning that lambda expression in a1 initializer returns.
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(2, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[0].FlowAnalysisAnnotations);
Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[1].FlowAnalysisAnnotations);
}
[Fact]
public void LambdaAttributes_UnmanagedCallersOnly()
{
var source =
@"using System;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
Action a = [UnmanagedCallersOnly] static () => { };
}
}";
var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,21): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// Action a = [UnmanagedCallersOnly] static () => { };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 21));
}
[Fact]
public void LambdaParameterAttributes_OptionalAndDefaultValueAttributes()
{
var source =
@"using System;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
Action<int> a1 = ([Optional, DefaultParameterValue(2)] int i) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single();
var parameter = (SourceParameterSymbol)lambda.Parameters[0];
Assert.True(parameter.HasOptionalAttribute);
Assert.False(parameter.HasExplicitDefaultValue);
Assert.Equal(2, parameter.DefaultValueFromAttributes.Value);
}
[ConditionalFact(typeof(DesktopOnly))]
public void LambdaParameterAttributes_WellKnownAttributes()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
Action<object> a1 = ([IDispatchConstant] object obj) => { };
Action<object> a2 = ([IUnknownConstant] object obj) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(2, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.True(lambdas[0].Parameters[0].IsIDispatchConstant);
Assert.True(lambdas[1].Parameters[0].IsIUnknownConstant);
}
[Fact]
public void LambdaParameterAttributes_NullableAttributes_01()
{
var source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Action<object> a1 = ([AllowNull][MaybeNullWhen(false)] object obj) => { };
Action<object, object> a2 = (object x, [NotNullIfNotNull(""x"")] object y) => { };
}
}";
var comp = CreateCompilation(
new[] { source, AllowNullAttributeDefinition, MaybeNullWhenAttributeDefinition, NotNullIfNotNullAttributeDefinition },
parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(2, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Equal(FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.MaybeNullWhenFalse, lambdas[0].Parameters[0].FlowAnalysisAnnotations);
Assert.Equal(new[] { "x" }, lambdas[1].Parameters[1].NotNullIfParameterNotNull);
}
[Fact]
public void LambdaParameterAttributes_NullableAttributes_02()
{
var source =
@"#nullable enable
using System.Diagnostics.CodeAnalysis;
delegate bool D(out object? obj);
class Program
{
static void Main()
{
D d = ([NotNullWhen(true)] out object? obj) =>
{
obj = null;
return true;
};
}
}";
var comp = CreateCompilation(new[] { source, NotNullWhenAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Should report WRN_ParameterConditionallyDisallowsNull.
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var lambda = GetLambdaSymbol(model, expr);
Assert.Equal(FlowAnalysisAnnotations.NotNullWhenTrue, lambda.Parameters[0].FlowAnalysisAnnotations);
}
[Fact]
public void LambdaReturnType_01()
{
var source =
@"using System;
class Program
{
static void F<T>()
{
Func<T> f1 = T () => default;
Func<T, T> f2 = T (x) => { return x; };
Func<T, T> f3 = T (T x) => x;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,22): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater.
// Func<T> f1 = T () => default;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(6, 22),
// (7,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater.
// Func<T, T> f2 = T (x) => { return x; };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(7, 25),
// (8,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater.
// Func<T, T> f3 = T (T x) => x;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(8, 25));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaReturnType_02()
{
var source =
@"using System;
class Program
{
static void F<T, U>()
{
Func<T> f1;
Func<U> f2;
f1 = T () => default;
f2 = T () => default;
f1 = U () => default;
f2 = U () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type
// f2 = T () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14),
// (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type
// f1 = U () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14));
}
[Fact]
public void LambdaReturnType_03()
{
var source =
@"using System;
class Program
{
static void F<T, U>() where U : T
{
Func<T> f1;
Func<U> f2;
f1 = T () => default;
f2 = T () => default;
f1 = U () => default;
f2 = U () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type
// f2 = T () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14),
// (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type
// f1 = U () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14));
}
[Fact]
public void LambdaReturnType_04()
{
var source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void F<T, U>()
{
Expression<Func<T>> e1;
Expression<Func<U>> e2;
e1 = T () => default;
e2 = T () => default;
e1 = U () => default;
e2 = U () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<U>>' because the return type does not match the delegate return type
// e2 = T () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<U>>").WithLocation(10, 14),
// (11,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<T>>' because the return type does not match the delegate return type
// e1 = U () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<T>>").WithLocation(11, 14));
}
[Fact]
public void LambdaReturnType_05()
{
var source =
@"#nullable enable
using System;
class Program
{
static void Main()
{
Func<dynamic> f1 = object () => default!;
Func<(int, int)> f2 = (int X, int Y) () => default;
Func<string?> f3 = string () => default!;
Func<IntPtr> f4 = nint () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes).
// Func<string?> f3 = string () => default!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => default!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28));
}
[Fact]
public void LambdaReturnType_06()
{
var source =
@"#nullable enable
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<object>> e1 = dynamic () => default!;
Expression<Func<(int X, int Y)>> e2 = (int, int) () => default;
Expression<Func<string>> e3 = string? () => default;
Expression<Func<nint>> e4 = IntPtr () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,39): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes).
// Expression<Func<string>> e3 = string? () => default;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => default").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 39));
}
[Fact]
public void LambdaReturnType_07()
{
var source =
@"#nullable enable
using System;
struct S<T> { }
class Program
{
static void Main()
{
Delegate d1 = string? () => default;
Delegate d2 = string () => default;
Delegate d3 = S<object?> () => default(S<object?>);
Delegate d4 = S<object?> () => default(S<object>);
Delegate d5 = S<object> () => default(S<object?>);
Delegate d6 = S<object> () => default(S<object>);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,36): warning CS8603: Possible null reference return.
// Delegate d2 = string () => default;
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(9, 36),
// (11,40): warning CS8619: Nullability of reference types in value of type 'S<object>' doesn't match target type 'S<object?>'.
// Delegate d4 = S<object?> () => default(S<object>);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object>)").WithArguments("S<object>", "S<object?>").WithLocation(11, 40),
// (12,39): warning CS8619: Nullability of reference types in value of type 'S<object?>' doesn't match target type 'S<object>'.
// Delegate d5 = S<object> () => default(S<object?>);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object?>)").WithArguments("S<object?>", "S<object>").WithLocation(12, 39));
}
[Fact]
public void LambdaReturnType_08()
{
var source =
@"#nullable enable
using System;
struct S<T> { }
class Program
{
static void Main()
{
Func<string?> f1 = string? () => throw null!;
Func<string?> f2 = string () => throw null!;
Func<string> f3 = string? () => throw null!;
Func<string> f4 = string () => throw null!;
Func<S<object?>> f5 = S<object?> () => throw null!;
Func<S<object?>> f6 = S<object> () => throw null!;
Func<S<object>> f7 = S<object?> () => throw null!;
Func<S<object>> f8 = S<object> () => throw null!;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes).
// Func<string?> f2 = string () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => throw null!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28),
// (10,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes).
// Func<string> f3 = string? () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => throw null!").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 27),
// (13,31): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object?>>' (possibly because of nullability attributes).
// Func<S<object?>> f6 = S<object> () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object> () => throw null!").WithArguments("lambda expression", "System.Func<S<object?>>").WithLocation(13, 31),
// (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object>>' (possibly because of nullability attributes).
// Func<S<object>> f7 = S<object?> () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object?> () => throw null!").WithArguments("lambda expression", "System.Func<S<object>>").WithLocation(14, 30));
}
[Fact]
public void LambdaReturnType_09()
{
var source =
@"#nullable enable
struct S<T> { }
delegate ref T D1<T>();
delegate ref readonly T D2<T>();
class Program
{
static void Main()
{
D1<S<object?>> f1 = (ref S<object?> () => throw null!);
D1<S<object?>> f2 = (ref S<object> () => throw null!);
D1<S<object>> f3 = (ref S<object?> () => throw null!);
D1<S<object>> f4 = (ref S<object> () => throw null!);
D2<S<object?>> f5 = (ref readonly S<object?> () => throw null!);
D2<S<object?>> f6 = (ref readonly S<object> () => throw null!);
D2<S<object>> f7 = (ref readonly S<object?> () => throw null!);
D2<S<object>> f8 = (ref readonly S<object> () => throw null!);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object?>>' (possibly because of nullability attributes).
// D1<S<object?>> f2 = (ref S<object> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object> () => throw null!").WithArguments("lambda expression", "D1<S<object?>>").WithLocation(10, 30),
// (11,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object>>' (possibly because of nullability attributes).
// D1<S<object>> f3 = (ref S<object?> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object?> () => throw null!").WithArguments("lambda expression", "D1<S<object>>").WithLocation(11, 29),
// (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object?>>' (possibly because of nullability attributes).
// D2<S<object?>> f6 = (ref readonly S<object> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object> () => throw null!").WithArguments("lambda expression", "D2<S<object?>>").WithLocation(14, 30),
// (15,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object>>' (possibly because of nullability attributes).
// D2<S<object>> f7 = (ref readonly S<object?> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object?> () => throw null!").WithArguments("lambda expression", "D2<S<object>>").WithLocation(15, 29));
}
[Fact]
public void LambdaReturnType_10()
{
var source =
@"delegate T D1<T>(ref T t);
delegate ref T D2<T>(ref T t);
delegate ref readonly T D3<T>(ref T t);
class Program
{
static void F<T>()
{
D1<T> d1;
D2<T> d2;
D3<T> d3;
d1 = T (ref T t) => t;
d2 = T (ref T t) => t;
d3 = T (ref T t) => t;
d1 = (ref T (ref T t) => ref t);
d2 = (ref T (ref T t) => ref t);
d3 = (ref T (ref T t) => ref t);
d1 = (ref readonly T (ref T t) => ref t);
d2 = (ref readonly T (ref T t) => ref t);
d3 = (ref readonly T (ref T t) => ref t);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (12,14): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type
// d2 = T (ref T t) => t;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D2<T>").WithLocation(12, 14),
// (13,14): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type
// d3 = T (ref T t) => t;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D3<T>").WithLocation(13, 14),
// (14,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type
// d1 = (ref T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(14, 15),
// (16,15): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type
// d3 = (ref T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D3<T>").WithLocation(16, 15),
// (17,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type
// d1 = (ref readonly T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(17, 15),
// (18,15): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type
// d2 = (ref readonly T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D2<T>").WithLocation(18, 15));
}
[Fact]
public void LambdaReturnType_11()
{
var source =
@"using System;
class Program
{
static void Main()
{
Delegate d;
d = (ref void () => { });
d = (ref readonly void () => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,14): error CS8917: The delegate type could not be inferred.
// d = (ref void () => { });
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 14),
// (7,18): error CS1547: Keyword 'void' cannot be used in this context
// d = (ref void () => { });
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 18),
// (8,14): error CS8917: The delegate type could not be inferred.
// d = (ref readonly void () => { });
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref readonly void () => { }").WithLocation(8, 14),
// (8,27): error CS1547: Keyword 'void' cannot be used in this context
// d = (ref readonly void () => { });
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(8, 27));
}
[WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")]
[ConditionalFact(typeof(DesktopOnly))]
public void LambdaReturnType_12()
{
var source =
@"using System;
class Program
{
static void Main()
{
Delegate d;
d = TypedReference () => throw null;
d = RuntimeArgumentHandle () => throw null;
d = ArgIterator () => throw null;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'TypedReference'
// d = TypedReference () => throw null;
Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference").WithLocation(7, 13),
// (7,13): error CS8917: The delegate type could not be inferred.
// d = TypedReference () => throw null;
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "TypedReference () => throw null").WithLocation(7, 13),
// (8,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'RuntimeArgumentHandle'
// d = RuntimeArgumentHandle () => throw null;
Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 13),
// (8,13): error CS8917: The delegate type could not be inferred.
// d = RuntimeArgumentHandle () => throw null;
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "RuntimeArgumentHandle () => throw null").WithLocation(8, 13),
// (9,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'ArgIterator'
// d = ArgIterator () => throw null;
Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(9, 13),
// (9,13): error CS8917: The delegate type could not be inferred.
// d = ArgIterator () => throw null;
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ArgIterator () => throw null").WithLocation(9, 13));
}
[Fact]
public void LambdaReturnType_13()
{
var source =
@"static class S { }
delegate S D();
class Program
{
static void Main()
{
D d = S () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,15): error CS0722: 'S': static types cannot be used as return types
// D d = S () => default;
Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S").WithArguments("S").WithLocation(7, 15));
}
[Fact]
public void LambdaReturnType_14()
{
var source =
@"using System;
class Program
{
static void Main()
{
Delegate d = async int () => 0;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,35): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T>
// Delegate d = async int () => 0;
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=>").WithLocation(6, 35),
// (6,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// Delegate d = async int () => 0;
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 35));
}
[Fact]
public void LambdaReturnType_15()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate ref Task D(string s);
class Program
{
static void Main()
{
Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,23): error CS8917: The delegate type could not be inferred.
// Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "async ref Task (s) => { _ = s.Length; await Task.Yield(); }").WithLocation(8, 23),
// (8,29): error CS1073: Unexpected token 'ref'
// Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29),
// (9,22): error CS1073: Unexpected token 'ref'
// D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22));
}
[Fact]
public void LambdaReturnType_16()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate ref Task D(string s);
class Program
{
static void Main()
{
Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,29): error CS1073: Unexpected token 'ref'
// Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29),
// (9,22): error CS1073: Unexpected token 'ref'
// D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22));
}
[Fact]
public void LambdaReturnType_17()
{
var source =
@"#nullable enable
using System;
class Program
{
static void F(string? x, string y)
{
Func<string?> f1 = string () => { if (x is null) return x; return y; };
Func<string> f2 = string? () => { if (x is not null) return x; return y; };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes).
// Func<string?> f1 = string () => { if (x is null) return x; return y; };
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => { if (x is null) return x; return y; }").WithArguments("lambda expression", "System.Func<string?>").WithLocation(7, 28),
// (7,65): warning CS8603: Possible null reference return.
// Func<string?> f1 = string () => { if (x is null) return x; return y; };
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(7, 65),
// (8,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes).
// Func<string> f2 = string? () => { if (x is not null) return x; return y; };
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => { if (x is not null) return x; return y; }").WithArguments("lambda expression", "System.Func<string>").WithLocation(8, 27));
}
[Fact]
public void LambdaReturnType_CustomModifiers_01()
{
var sourceA =
@".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { }
.method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) Invoke () runtime managed { }
.method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { }
.method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { }
}";
var refA = CompileIL(sourceA);
var sourceB =
@"class Program
{
static void F(D d)
{
System.Console.WriteLine(d());
}
static void Main()
{
F(() => 1);
F(int () => 2);
}
}";
CompileAndVerify(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview, expectedOutput:
@"1
2");
}
[Fact]
public void LambdaReturnType_CustomModifiers_02()
{
var sourceA =
@".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { }
.method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) Invoke () runtime managed { }
.method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { }
.method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { }
}";
var refA = CompileIL(sourceA);
var sourceB =
@"class Program
{
static void F(D d)
{
System.Console.WriteLine(d());
}
static void Main()
{
F(() => 1);
F(int () => 2);
}
}";
var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,34): error CS0570: 'D.Invoke()' is not supported by the language
// System.Console.WriteLine(d());
Diagnostic(ErrorCode.ERR_BindToBogus, "d()").WithArguments("D.Invoke()").WithLocation(5, 34),
// (9,11): error CS0570: 'D.Invoke()' is not supported by the language
// F(() => 1);
Diagnostic(ErrorCode.ERR_BindToBogus, "() => 1").WithArguments("D.Invoke()").WithLocation(9, 11),
// (10,11): error CS0570: 'D.Invoke()' is not supported by the language
// F(int () => 2);
Diagnostic(ErrorCode.ERR_BindToBogus, "int () => 2").WithArguments("D.Invoke()").WithLocation(10, 11));
}
[Fact]
public void LambdaReturnType_UseSiteErrors()
{
var sourceA =
@".class public sealed A extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 FF 00 00 )
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using System;
class B
{
static void F<T>(Func<T> f) { }
static void Main()
{
F(A () => default);
}
}";
var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,11): error CS0648: 'A' is a type not supported by the language
// F(A () => default);
Diagnostic(ErrorCode.ERR_BogusType, "A").WithArguments("A").WithLocation(7, 11));
}
[Fact]
public void AsyncLambdaParameters_01()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate Task D(ref string s);
class Program
{
static void Main()
{
Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,41): error CS1988: Async methods cannot have ref, in or out parameters
// Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(8, 41),
// (9,34): error CS1988: Async methods cannot have ref, in or out parameters
// D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(9, 34));
}
[ConditionalFact(typeof(DesktopOnly))]
public void AsyncLambdaParameters_02()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate void D1(TypedReference r);
delegate void D2(RuntimeArgumentHandle h);
delegate void D3(ArgIterator i);
class Program
{
static void Main()
{
D1 d1 = async (TypedReference r) => { await Task.Yield(); };
D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); };
D3 d3 = async (ArgIterator i) => { await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,39): error CS4012: Parameters or locals of type 'TypedReference' cannot be declared in async methods or async lambda expressions.
// D1 d1 = async (TypedReference r) => { await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "r").WithArguments("System.TypedReference").WithLocation(10, 39),
// (11,46): error CS4012: Parameters or locals of type 'RuntimeArgumentHandle' cannot be declared in async methods or async lambda expressions.
// D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "h").WithArguments("System.RuntimeArgumentHandle").WithLocation(11, 46),
// (12,36): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// D3 d3 = async (ArgIterator i) => { await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "i").WithArguments("System.ArgIterator").WithLocation(12, 36));
}
[Fact]
public void BestType_01()
{
var source =
@"using System;
class A { }
class B1 : A { }
class B2 : A { }
interface I { }
class C1 : I { }
class C2 : I { }
class Program
{
static void F<T>(Func<bool, T> f) { }
static void Main()
{
F((bool b) => { if (b) return new B1(); return new B2(); });
F((bool b) => { if (b) return new C1(); return new C2(); });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (13,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F((bool b) => { if (b) return new B1(); return new B2(); });
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(13, 9),
// (14,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F((bool b) => { if (b) return new C1(); return new C2(); });
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(14, 9));
}
// As above but with explicit return type.
[Fact]
public void BestType_02()
{
var source =
@"using System;
class A { }
class B1 : A { }
class B2 : A { }
interface I { }
class C1 : I { }
class C2 : I { }
class Program
{
static void F<T>(Func<bool, T> f) { Console.WriteLine(typeof(T)); }
static void Main()
{
F(A (bool b) => { if (b) return new B1(); return new B2(); });
F(I (bool b) => { if (b) return new C1(); return new C2(); });
}
}";
CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput:
@"A
I");
}
[Fact]
public void BestType_03()
{
var source =
@"using System;
class A { }
class B1 : A { }
class B2 : A { }
class Program
{
static void F<T>(Func<T> x, Func<T> y) { }
static void Main()
{
F(B2 () => null, B2 () => null);
F(A () => null, B2 () => null);
F(B1 () => null, B2 () => null);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (11,25): error CS8934: Cannot convert lambda expression to type 'Func<A>' because the return type does not match the delegate return type
// F(A () => null, B2 () => null);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "B2 () => null").WithArguments("lambda expression", "System.Func<A>").WithLocation(11, 25),
// (12,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(B1 () => null, B2 () => null);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(12, 9));
}
[Fact]
public void TypeInference_01()
{
var source =
@"using System;
class Program
{
static void F<T>(Func<object, T> f)
{
Console.WriteLine(typeof(T));
}
static void Main()
{
F(long (o) => 1);
}
}";
CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"System.Int64");
}
// Should method type inference make an explicit type inference
// from the lambda expression return type?
[Fact]
public void TypeInference_02()
{
var source =
@"using System;
class Program
{
static void F<T>(Func<T, T> f)
{
Console.WriteLine(typeof(T));
}
static void Main()
{
F(int (i) => i);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(int (i) => i);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T, T>)").WithLocation(10, 9));
}
// CS4031 is not reported for async lambda in [SecurityCritical] type.
[Fact]
[WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")]
public void SecurityCritical_AsyncLambda()
{
var source =
@"using System;
using System.Security;
using System.Threading.Tasks;
[SecurityCritical]
class Program
{
static void Main()
{
Func<Task> f = async () => await Task.Yield();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
// CS4031 is not reported for async lambda in [SecurityCritical] type.
[Fact]
[WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")]
public void SecurityCritical_AsyncLambda_AttributeArgument()
{
var source =
@"using System;
using System.Security;
using System.Threading.Tasks;
class A : Attribute
{
internal A(int i) { }
}
[SecurityCritical]
[A(F(async () => await Task.Yield()))]
class Program
{
internal static int F(Func<Task> f) => 0;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(F(async () => await Task.Yield()))]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F(async () => await Task.Yield())").WithLocation(9, 4));
}
private static LambdaSymbol GetLambdaSymbol(SemanticModel model, LambdaExpressionSyntax syntax)
{
return model.GetSymbolInfo(syntax).Symbol.GetSymbol<LambdaSymbol>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class LambdaTests : CSharpTestBase
{
[Fact, WorkItem(37456, "https://github.com/dotnet/roslyn/issues/37456")]
public void Verify37456()
{
var comp = CreateCompilation(@"
using System;
using System.Collections.Generic;
using System.Linq;
public static partial class EnumerableEx
{
public static void Join1<TA, TKey, T>(this IEnumerable<TA> a, Func<TA, TKey> aKey, Func<TA, T> aSel, Func<TA, TA, T> sel)
{
KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v);
_ = a.GroupJoin(a, aKey, aKey, (f, ss) => Pair(f, ss.Select(s => Pair(true, s)))); // simplified repro
}
public static IEnumerable<T> Join2<TA, TB, TKey, T>(this IEnumerable<TA> a, IEnumerable<TB> b, Func<TA, TKey> aKey, Func<TB, TKey> bKey, Func<TA, T> aSel, Func<TA, TB, T> sel, IEqualityComparer<TKey> comp)
{
KeyValuePair<TK, TV> Pair<TK, TV>(TK k, TV v) => new KeyValuePair<TK, TV>(k, v);
return
from j in a.GroupJoin(b, aKey, bKey, (f, ss) => Pair(f, from s in ss select Pair(true, s)), comp)
from s in j.Value.DefaultIfEmpty()
select s.Key ? sel(j.Key, s.Value) : aSel(j.Key);
}
}");
comp.VerifyDiagnostics();
CompileAndVerify(comp);
// emitting should not hang
}
[Fact, WorkItem(608181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608181")]
public void BadInvocationInLambda()
{
var src = @"
using System;
using System.Linq.Expressions;
class C
{
Expression<Action<dynamic>> e = x => new object[](x);
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(src);
comp.VerifyDiagnostics(
// (7,52): error CS1586: Array creation must have array size or array initializer
// Expression<Action<dynamic>> e = x => new object[](x);
Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52)
);
}
[Fact]
public void TestLambdaErrors01()
{
var comp = CreateCompilationWithMscorlib40AndSystemCore(@"
using System;
using System.Linq.Expressions;
namespace System.Linq.Expressions
{
public class Expression<T> {}
}
class C
{
delegate void D1(ref int x, out int y, int z);
delegate void D2(out int x);
void M()
{
int q1 = ()=>1;
int q2 = delegate { return 1; };
Func<int> q3 = x3=>1;
Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type
Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type
D1 q6 = (double x6, ref int y6, ref int z6)=>1;
// COMPATIBILITY: The C# 4 compiler produces two errors:
//
// error CS1676: Parameter 2 must be declared with the 'out' keyword
// error CS1688: Cannot convert anonymous method block without a parameter list
// to delegate type 'D1' because it has one or more out parameters
//
// This seems redundant (because there is no 'parameter 2' in the source code)
// I propose that we eliminate the first error.
D1 q7 = delegate {};
Frob q8 = ()=>{};
D2 q9 = x9=>{};
D1 q10 = (x10,y10,z10)=>{};
// COMPATIBILITY: The C# 4 compiler produces two errors:
//
// error CS0127: Since 'System.Action' returns void, a return keyword must
// not be followed by an object expression
//
// error CS1662: Cannot convert lambda expression to delegate type 'System.Action'
// because some of the return types in the block are not implicitly convertible to
// the delegate return type
//
// The problem is adequately characterized by the first message; I propose we
// eliminate the second, which seems both redundant and wrong.
Action q11 = ()=>{ return 1; };
Action q12 = ()=>1;
Func<int> q13 = ()=>{ if (false) return 1; };
Func<int> q14 = ()=>123.456;
// Note that the type error is still an error even if the offending
// return is unreachable.
Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
// In the native compiler these errors were caught at parse time. In Roslyn, these are now semantic
// analysis errors. See changeset 1674 for details.
Action<int[]> q16 = delegate (params int[] p) { };
Action<string[]> q17 = (params string[] s)=>{};
Action<int, double[]> q18 = (int x, params double[] s)=>{};
object q19 = new Action( (int x)=>{} );
Expression<int> ex1 = ()=>1;
}
}");
comp.VerifyDiagnostics(
// (16,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type
// int q1 = ()=>1;
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "()=>1").WithArguments("lambda expression", "int").WithLocation(16, 18),
// (17,18): error CS1660: Cannot convert anonymous method to type 'int' because it is not a delegate type
// int q2 = delegate { return 1; };
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate { return 1; }").WithArguments("anonymous method", "int").WithLocation(17, 18),
// (18,24): error CS1593: Delegate 'Func<int>' does not take 1 arguments
// Func<int> q3 = x3=>1;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "x3=>1").WithArguments("System.Func<int>", "1").WithLocation(18, 24),
// (19,37): error CS0234: The type or namespace name 'Itn23' does not exist in the namespace 'System' (are you missing an assembly reference?)
// Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Itn23").WithArguments("Itn23", "System").WithLocation(19, 37),
// (20,35): error CS0234: The type or namespace name 'Duobel' does not exist in the namespace 'System' (are you missing an assembly reference?)
// Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type
Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Duobel").WithArguments("Duobel", "System").WithLocation(20, 35),
// (20,27): error CS1593: Delegate 'Func<double>' does not take 1 arguments
// Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(System.Duobel x5)=>1").WithArguments("System.Func<double>", "1").WithLocation(20, 27),
// (21,17): error CS1661: Cannot convert lambda expression to delegate type 'C.D1' because the parameter types do not match the delegate parameter types
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double x6, ref int y6, ref int z6)=>1").WithArguments("lambda expression", "C.D1").WithLocation(21, 17),
// (21,25): error CS1678: Parameter 1 is declared as type 'double' but should be 'ref int'
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_BadParamType, "x6").WithArguments("1", "", "double", "ref ", "int").WithLocation(21, 25),
// (21,37): error CS1676: Parameter 2 must be declared with the 'out' keyword
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_BadParamRef, "y6").WithArguments("2", "out").WithLocation(21, 37),
// (21,49): error CS1677: Parameter 3 should not be declared with the 'ref' keyword
// D1 q6 = (double x6, ref int y6, ref int z6)=>1;
Diagnostic(ErrorCode.ERR_BadParamExtraRef, "z6").WithArguments("3", "ref").WithLocation(21, 49),
// (32,17): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'C.D1' because it has one or more out parameters
// D1 q7 = delegate {};
Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, "delegate {}").WithArguments("C.D1").WithLocation(32, 17),
// (34,9): error CS0246: The type or namespace name 'Frob' could not be found (are you missing a using directive or an assembly reference?)
// Frob q8 = ()=>{};
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Frob").WithArguments("Frob").WithLocation(34, 9),
// (36,17): error CS1676: Parameter 1 must be declared with the 'out' keyword
// D2 q9 = x9=>{};
Diagnostic(ErrorCode.ERR_BadParamRef, "x9").WithArguments("1", "out").WithLocation(36, 17),
// (38,19): error CS1676: Parameter 1 must be declared with the 'ref' keyword
// D1 q10 = (x10,y10,z10)=>{};
Diagnostic(ErrorCode.ERR_BadParamRef, "x10").WithArguments("1", "ref").WithLocation(38, 19),
// (38,23): error CS1676: Parameter 2 must be declared with the 'out' keyword
// D1 q10 = (x10,y10,z10)=>{};
Diagnostic(ErrorCode.ERR_BadParamRef, "y10").WithArguments("2", "out").WithLocation(38, 23),
// (52,28): error CS8030: Anonymous function converted to a void returning delegate cannot return a value
// Action q11 = ()=>{ return 1; };
Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(52, 28),
// (54,26): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// Action q12 = ()=>1;
Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(54, 26),
// (56,42): warning CS0162: Unreachable code detected
// Func<int> q13 = ()=>{ if (false) return 1; };
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(56, 42),
// (56,27): error CS1643: Not all code paths return a value in lambda expression of type 'Func<int>'
// Func<int> q13 = ()=>{ if (false) return 1; };
Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "=>").WithArguments("lambda expression", "System.Func<int>").WithLocation(56, 27),
// (58,29): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?)
// Func<int> q14 = ()=>123.456;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "123.456").WithArguments("double", "int").WithLocation(58, 29),
// (58,29): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<int> q14 = ()=>123.456;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "123.456").WithArguments("lambda expression").WithLocation(58, 29),
// (62,51): error CS0266: Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?)
// Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1m").WithArguments("decimal", "double").WithLocation(62, 51),
// (62,51): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1m").WithArguments("lambda expression").WithLocation(62, 51),
// (62,44): warning CS0162: Unreachable code detected
// Func<double> q15 = ()=>{if (false) return 1m; else return 0; };
Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(62, 44),
// (66,39): error CS1670: params is not valid in this context
// Action<int[]> q16 = delegate (params int[] p) { };
Diagnostic(ErrorCode.ERR_IllegalParams, "params int[] p").WithLocation(66, 39),
// (67,33): error CS1670: params is not valid in this context
// Action<string[]> q17 = (params string[] s)=>{};
Diagnostic(ErrorCode.ERR_IllegalParams, "params string[] s").WithLocation(67, 33),
// (68,45): error CS1670: params is not valid in this context
// Action<int, double[]> q18 = (int x, params double[] s)=>{};
Diagnostic(ErrorCode.ERR_IllegalParams, "params double[] s").WithLocation(68, 45),
// (70,34): error CS1593: Delegate 'Action' does not take 1 arguments
// object q19 = new Action( (int x)=>{} );
Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int x)=>{}").WithArguments("System.Action", "1").WithLocation(70, 34),
// (72,9): warning CS0436: The type 'Expression<T>' in '' conflicts with the imported type 'Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''.
// Expression<int> ex1 = ()=>1;
Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<int>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>").WithLocation(72, 9),
// (72,31): error CS0835: Cannot convert lambda to an expression tree whose type argument 'int' is not a delegate type
// Expression<int> ex1 = ()=>1;
Diagnostic(ErrorCode.ERR_ExpressionTreeMustHaveDelegate, "()=>1").WithArguments("int").WithLocation(72, 31)
);
}
[Fact] // 5368
public void TestLambdaErrors02()
{
string code = @"
class C
{
void M()
{
System.Func<int, int> del = x => x + 1;
}
}";
var compilation = CreateCompilation(code);
compilation.VerifyDiagnostics(); // no errors expected
}
[WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")]
[Fact]
public void TestLambdaErrors03()
{
string source = @"
using System;
interface I : IComparable<IComparable<I>> { }
class C
{
static void Goo(Func<IComparable<I>> x) { }
static void Goo(Func<I> x) {}
static void M()
{
Goo(() => null);
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Goo(Func<IComparable<I>>)' and 'C.Goo(Func<I>)'
// Goo(() => null);
Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("C.Goo(System.Func<System.IComparable<I>>)", "C.Goo(System.Func<I>)").WithLocation(12, 9));
}
[WorkItem(18645, "https://github.com/dotnet/roslyn/issues/18645")]
[Fact]
public void LambdaExpressionTreesErrors()
{
string source = @"
using System;
using System.Linq.Expressions;
class C
{
void M()
{
Expression<Func<int,int>> ex1 = () => 1;
Expression<Func<int,int>> ex2 = (double d) => 1;
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (9,41): error CS1593: Delegate 'Func<int, int>' does not take 0 arguments
// Expression<Func<int,int>> ex1 = () => 1;
Diagnostic(ErrorCode.ERR_BadDelArgCount, "() => 1").WithArguments("System.Func<int, int>", "0").WithLocation(9, 41),
// (10,41): error CS1661: Cannot convert lambda expression to type 'Expression<Func<int, int>>' because the parameter types do not match the delegate parameter types
// Expression<Func<int,int>> ex2 = (double d) => 1;
Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double d) => 1").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<int, int>>").WithLocation(10, 41),
// (10,49): error CS1678: Parameter 1 is declared as type 'double' but should be 'int'
// Expression<Func<int,int>> ex2 = (double d) => 1;
Diagnostic(ErrorCode.ERR_BadParamType, "d").WithArguments("1", "", "double", "", "int").WithLocation(10, 49));
}
[WorkItem(539976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539976")]
[Fact]
public void LambdaArgumentToOverloadedDelegate()
{
var text = @"class W
{
delegate T Func<A0, T>(A0 a0);
static int F(Func<short, int> f) { return 0; }
static int F(Func<short, double> f) { return 1; }
static int Main()
{
return F(c => c);
}
}
";
var comp = CreateCompilation(Parse(text));
comp.VerifyDiagnostics();
}
[WorkItem(528044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528044")]
[Fact]
public void MissingReferenceInOverloadResolution()
{
var text1 = @"
using System;
public static class A
{
public static void Goo(Func<B, object> func) { }
public static void Goo(Func<C, object> func) { }
}
public class B
{
public Uri GetUrl()
{
return null;
}
}
public class C
{
public string GetUrl()
{
return null;
}
}";
var comp1 = CreateCompilationWithMscorlib40(
new[] { Parse(text1) },
new[] { TestMetadata.Net451.System });
var text2 = @"
class Program
{
static void Main()
{
A.Goo(x => x.GetUrl());
}
}
";
var comp2 = CreateCompilationWithMscorlib40(
new[] { Parse(text2) },
new[] { new CSharpCompilationReference(comp1) });
Assert.Equal(0, comp2.GetDiagnostics().Count());
}
[WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")]
[Fact()]
public void OverloadResolutionWithEmbeddedInteropType()
{
var text1 = @"
using System;
using System.Collections.Generic;
using stdole;
public static class A
{
public static void Goo(Func<X> func)
{
System.Console.WriteLine(""X"");
}
public static void Goo(Func<Y> func)
{
System.Console.WriteLine(""Y"");
}
}
public delegate void X(List<IDispatch> addin);
public delegate void Y(List<string> addin);
";
var comp1 = CreateCompilation(
Parse(text1),
new[] { TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) },
options: TestOptions.ReleaseDll);
var text2 = @"
public class Program
{
public static void Main()
{
A.Goo(() => delegate { });
}
}
";
var comp2 = CreateCompilation(
Parse(text2),
new MetadataReference[]
{
new CSharpCompilationReference(comp1),
TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true)
},
options: TestOptions.ReleaseExe);
CompileAndVerify(comp2, expectedOutput: "Y").Diagnostics.Verify();
var comp3 = CreateCompilation(
Parse(text2),
new MetadataReference[]
{
comp1.EmitToImageReference(),
TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true)
},
options: TestOptions.ReleaseExe);
CompileAndVerify(comp3, expectedOutput: "Y").Diagnostics.Verify();
}
[WorkItem(6358, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidExpressionInvolveLambdaOperator()
{
var text1 = @"
class C
{
static void X()
{
int x=0; int y=0;
if(x-=>*y) // CS1525
return;
return;
}
}
";
var comp = CreateCompilation(Parse(text1));
var errs = comp.GetDiagnostics();
Assert.True(0 < errs.Count(), "Diagnostics not empty");
Assert.True(0 < errs.Where(e => e.Code == 1525).Select(e => e).Count(), "Diagnostics contains CS1525");
}
[WorkItem(540219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540219")]
[Fact]
public void OverloadResolutionWithStaticType()
{
var vbSource = @"
Imports System
Namespace Microsoft.VisualBasic.CompilerServices
<System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)>
Public NotInheritable Class StandardModuleAttribute
Inherits System.Attribute
Public Sub New()
MyBase.New()
End Sub
End Class
End Namespace
Public Module M
Sub Goo(x as Action(Of String))
End Sub
Sub Goo(x as Action(Of GC))
End Sub
End Module
";
var vbProject = VisualBasic.VisualBasicCompilation.Create(
"VBProject",
references: new[] { MscorlibRef },
syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) });
var csSource = @"
class Program
{
static void Main()
{
M.Goo(x => { });
}
}
";
var metadataStream = new MemoryStream();
var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true));
Assert.True(emitResult.Success);
var csProject = CreateCompilation(
Parse(csSource),
new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) });
Assert.Equal(0, csProject.GetDiagnostics().Count());
}
[Fact]
public void OverloadResolutionWithStaticTypeError()
{
var vbSource = @"
Imports System
Namespace Microsoft.VisualBasic.CompilerServices
<System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)>
Public NotInheritable Class StandardModuleAttribute
Inherits System.Attribute
Public Sub New()
MyBase.New()
End Sub
End Class
End Namespace
Public Module M
Public Dim F As Action(Of GC)
End Module
";
var vbProject = VisualBasic.VisualBasicCompilation.Create(
"VBProject",
references: new[] { MscorlibRef },
syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) });
var csSource = @"
class Program
{
static void Main()
{
M.F = x=>{};
}
}
";
var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true));
var csProject = CreateCompilation(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) });
csProject.VerifyDiagnostics(
// (6,15): error CS0721: 'GC': static types cannot be used as parameters
// M.F = x=>{};
Diagnostic(ErrorCode.ERR_ParameterIsStaticClass, "x").WithArguments("System.GC").WithLocation(6, 15));
}
[WorkItem(540251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540251")]
[Fact]
public void AttributesCannotBeUsedInAnonymousMethods()
{
var csSource = @"
using System;
class Program
{
static void Main()
{
const string message = ""The parameter is obsolete"";
Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { };
}
}
";
var csProject = CreateCompilation(csSource);
csProject.VerifyEmitDiagnostics(
// (8,22): warning CS0219: The variable 'message' is assigned but its value is never used
// const string message = "The parameter is obsolete";
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "message").WithArguments("message").WithLocation(8, 22),
// (9,35): error CS7014: Attributes are not valid in this context.
// Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[ObsoleteAttribute(message)]").WithLocation(9, 35));
}
[WorkItem(540263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540263")]
[Fact]
public void ErrorsInUnboundLambdas()
{
var csSource = @"using System;
class Program
{
static void Main()
{
((Func<int>)delegate { return """"; })();
((Func<int>)delegate { })();
((Func<int>)delegate { 1 / 0; })();
}
}
";
CreateCompilation(csSource).VerifyDiagnostics(
// (7,39): error CS0029: Cannot implicitly convert type 'string' to 'int'
// ((Func<int>)delegate { return ""; })();
Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(7, 39),
// (7,39): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// ((Func<int>)delegate { return ""; })();
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("anonymous method").WithLocation(7, 39),
// (8,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>'
// ((Func<int>)delegate { })();
Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(8, 21),
// (9,32): error CS0020: Division by constant zero
// ((Func<int>)delegate { 1 / 0; })();
Diagnostic(ErrorCode.ERR_IntDivByZero, "1 / 0").WithLocation(9, 32),
// (9,32): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((Func<int>)delegate { 1 / 0; })();
Diagnostic(ErrorCode.ERR_IllegalStatement, "1 / 0").WithLocation(9, 32),
// (9,21): error CS1643: Not all code paths return a value in anonymous method of type 'Func<int>'
// ((Func<int>)delegate { 1 / 0; })();
Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate").WithArguments("anonymous method", "System.Func<int>").WithLocation(9, 21)
);
}
[WorkItem(540181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540181")]
[Fact]
public void ErrorInLambdaArgumentList()
{
var csSource = @"using System;
class Program
{
public Program(string x) : this(() => x) { }
static void Main(string[] args)
{
((Action<string>)(f => Console.WriteLine(f)))(nulF);
}
}";
CreateCompilation(csSource).VerifyDiagnostics(
// (5,37): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type
// public Program(string x) : this(() => x) { }
Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => x").WithArguments("lambda expression", "string").WithLocation(5, 37),
// (8,55): error CS0103: The name 'nulF' does not exist in the current context
// ((Action<string>)(f => Console.WriteLine(f)))(nulF);
Diagnostic(ErrorCode.ERR_NameNotInContext, "nulF").WithArguments("nulF").WithLocation(8, 55));
}
[WorkItem(541725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541725")]
[Fact]
public void DelegateCreationIsNotStatement()
{
var csSource = @"
delegate void D();
class Program
{
public static void Main(string[] args)
{
D d = () => new D(() => { });
new D(()=>{});
}
}";
// Though it is legal to have an object-creation-expression, because it might be useful
// for its side effects, a delegate-creation-expression is not allowed as a
// statement expression.
CreateCompilation(csSource).VerifyDiagnostics(
// (7,21): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// D d = () => new D(() => { });
Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(() => { })"),
// (8,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// new D(()=>{});
Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(()=>{})"));
}
[WorkItem(542336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542336")]
[Fact]
public void ThisInStaticContext()
{
var csSource = @"
delegate void D();
class Program
{
public static void Main(string[] args)
{
D d = () => {
object o = this;
};
}
}";
CreateCompilation(csSource).VerifyDiagnostics(
// (8,24): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer
// object o = this;
Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this")
);
}
[WorkItem(542431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542431")]
[Fact]
public void LambdaHasMoreParametersThanDelegate()
{
var csSource = @"
class C
{
static void Main()
{
System.Func<int> f = new System.Func<int>(r => 0);
}
}";
CreateCompilation(csSource).VerifyDiagnostics(
// (6,51): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments
Diagnostic(ErrorCode.ERR_BadDelArgCount, "r => 0").WithArguments("System.Func<int>", "1"));
}
[Fact, WorkItem(529054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529054")]
public void LambdaInDynamicCall()
{
var source = @"
public class Program
{
static void Main()
{
dynamic b = new string[] { ""AA"" };
bool exists = System.Array.Exists(b, o => o != ""BB"");
}
}";
CreateCompilation(source).VerifyDiagnostics(
// (7,46): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type.
// bool exists = System.Array.Exists(b, o => o != "BB");
Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, @"o => o != ""BB""")
);
}
[Fact, WorkItem(529389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529389")]
public void ParenthesizedLambdaInCastExpression()
{
var source = @"
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
int x = 1;
byte y = (byte) (x + x);
Func<int> f1 = (() => { return 1; });
Func<int> f2 = (Func<int>) (() => { return 2; });
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>().
Where(e => e.Kind() == SyntaxKind.AddExpression).Single();
var tinfo = model.GetTypeInfo(expr);
var conv = model.GetConversion(expr);
// Not byte
Assert.Equal("int", tinfo.Type.ToDisplayString());
var exprs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>();
expr = exprs.First();
tinfo = model.GetTypeInfo(expr);
conv = model.GetConversion(expr);
Assert.True(conv.IsAnonymousFunction, "LambdaConversion");
Assert.Null(tinfo.Type);
var sym = model.GetSymbolInfo(expr).Symbol;
Assert.NotNull(sym);
Assert.Equal(SymbolKind.Method, sym.Kind);
Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind);
expr = exprs.Last();
tinfo = model.GetTypeInfo(expr);
conv = model.GetConversion(expr);
Assert.True(conv.IsAnonymousFunction, "LambdaConversion");
Assert.Null(tinfo.Type);
sym = model.GetSymbolInfo(expr).Symbol;
Assert.NotNull(sym);
Assert.Equal(SymbolKind.Method, sym.Kind);
Assert.Equal(MethodKind.AnonymousFunction, (sym as IMethodSymbol).MethodKind);
}
[WorkItem(544594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544594")]
[Fact]
public void LambdaInEnumMemberDecl()
{
var csSource = @"
public class TestClass
{
public enum Test { aa = ((System.Func<int>)(() => 1))() }
Test MyTest = Test.aa;
public static void Main()
{
}
}
";
CreateCompilation(csSource).VerifyDiagnostics(
// (4,29): error CS0133: The expression being assigned to 'TestClass.Test.aa' must be constant
Diagnostic(ErrorCode.ERR_NotConstantExpression, "((System.Func<int>)(() => 1))()").WithArguments("TestClass.Test.aa"),
// (5,10): warning CS0414: The field 'TestClass.MyTest' is assigned but its value is never used
Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "MyTest").WithArguments("TestClass.MyTest"));
}
[WorkItem(544932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544932")]
[Fact]
public void AnonymousLambdaInEnumSubtraction()
{
string source = @"
class Test
{
enum E1 : byte
{
A = byte.MinValue,
C = 1
}
static void Main()
{
int j = ((System.Func<Test.E1>)(() => E1.A))() - E1.C;
System.Console.WriteLine(j);
}
}
";
string expectedOutput = @"255";
CompileAndVerify(new[] { source }, expectedOutput: expectedOutput);
}
[WorkItem(545156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545156")]
[Fact]
public void SpeculativelyBindOverloadResolution()
{
string source = @"
using System;
using System.Collections;
using System.Collections.Generic;
class Program
{
static void Main()
{
Goo(() => () => { var x = (IEnumerable<int>)null; return x; });
}
static void Goo(Func<Func<IEnumerable>> x) { }
static void Goo(Func<Func<IFormattable>> x) { }
}
";
var compilation = CreateCompilation(source);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single();
// Used to throw a NRE because of the ExpressionSyntax's null SyntaxTree.
model.GetSpeculativeSymbolInfo(
invocation.SpanStart,
SyntaxFactory.ParseExpression("Goo(() => () => { var x = null; return x; })"), // cast removed
SpeculativeBindingOption.BindAsExpression);
}
[WorkItem(545343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545343")]
[Fact]
public void LambdaUsingFieldInConstructor()
{
string source = @"
using System;
public class Derived
{
int field = 1;
Derived()
{
int local = 2;
// A lambda that captures a local and refers to an instance field.
Action a = () => Console.WriteLine(""Local = {0}, Field = {1}"", local, field);
// NullReferenceException if the ""this"" field of the display class hasn't been set.
a();
}
public static void Main()
{
Derived d = new Derived();
}
}";
CompileAndVerify(source, expectedOutput: "Local = 2, Field = 1");
}
[WorkItem(642222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642222")]
[Fact]
public void SpeculativelyBindOverloadResolutionAndInferenceWithError()
{
string source = @"
using System;using System.Linq.Expressions;
namespace IntellisenseBug
{
public class Program
{
void M(Mapper<FromData, ToData> mapper)
{
// Intellisense is broken here when you type . after the x:
mapper.Map(x => x/* */.
}
}
public class Mapper<TTypeFrom, TTypeTo>
{
public void Map<TPropertyFrom, TPropertyTo>(
Expression<Func<TTypeFrom, TPropertyFrom>> from,
Expression<Func<TTypeTo, TPropertyTo>> to)
{ }
}
public class FromData
{
public int Int { get; set; }
public string String { get; set; }
}
public class ToData
{
public int Id { get; set; }
public string Name
{
get; set;
}
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
// We don't actually require any particular diagnostics, but these are what we get.
compilation.VerifyDiagnostics(
// (10,36): error CS1001: Identifier expected
// mapper.Map(x => x/* */.
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (10,36): error CS1026: ) expected
// mapper.Map(x => x/* */.
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (10,36): error CS1002: ; expected
// mapper.Map(x => x/* */.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "")
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var xReference =
tree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType<ExpressionSyntax>()
.Where(e => e.ToFullString() == "x/* */")
.Last();
var typeInfo = model.GetTypeInfo(xReference);
Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("String"));
}
[WorkItem(722288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722288")]
[Fact]
public void CompletionInLambdaInIncompleteInvocation()
{
string source = @"
using System;
using System.Linq.Expressions;
public class SomeType
{
public string SomeProperty { get; set; }
}
public class IntelliSenseError
{
public static void Test1<T>(Expression<Func<T, object>> expr)
{
Console.WriteLine(((MemberExpression)expr.Body).Member.Name);
}
public static void Test2<T>(Expression<Func<T, object>> expr, bool additionalParameter)
{
Test1(expr);
}
public static void Main()
{
Test2<SomeType>(o => o/* */.
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
// We don't actually require any particular diagnostics, but these are what we get.
compilation.VerifyDiagnostics(
// (21,37): error CS1001: Identifier expected
// Test2<SomeType>(o => o/* */.
Diagnostic(ErrorCode.ERR_IdentifierExpected, ""),
// (21,37): error CS1026: ) expected
// Test2<SomeType>(o => o/* */.
Diagnostic(ErrorCode.ERR_CloseParenExpected, ""),
// (21,37): error CS1002: ; expected
// Test2<SomeType>(o => o/* */.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "")
);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var oReference =
tree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType<NameSyntax>()
.Where(e => e.ToFullString() == "o/* */")
.Last();
var typeInfo = model.GetTypeInfo(oReference);
Assert.NotNull(((ITypeSymbol)typeInfo.Type).GetMember("SomeProperty"));
}
[WorkItem(871896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871896")]
[Fact]
public void Bug871896()
{
string source = @"
using System.Threading;
using System.Threading.Tasks;
class TestDataPointBase
{
private readonly IVisualStudioIntegrationService integrationService;
protected void TryGetDocumentId(CancellationToken token)
{
DocumentId documentId = null;
if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
{
}
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.Single();
var model = compilation.GetSemanticModel(tree);
var oReference =
tree
.GetCompilationUnitRoot()
.DescendantNodes()
.OfType<ExpressionSyntax>()
.OrderByDescending(s => s.SpanStart);
foreach (var name in oReference)
{
CSharpExtensions.GetSymbolInfo(model, name);
}
// We should get a bunch of errors, but no asserts.
compilation.VerifyDiagnostics(
// (6,22): error CS0246: The type or namespace name 'IVisualStudioIntegrationService' could not be found (are you missing a using directive or an assembly reference?)
// private readonly IVisualStudioIntegrationService integrationService;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVisualStudioIntegrationService").WithArguments("IVisualStudioIntegrationService").WithLocation(6, 22),
// (9,9): error CS0246: The type or namespace name 'DocumentId' could not be found (are you missing a using directive or an assembly reference?)
// DocumentId documentId = null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "DocumentId").WithArguments("DocumentId").WithLocation(9, 9),
// (10,25): error CS0117: 'System.Threading.Tasks.Task' does not contain a definition for 'Run'
// if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
Diagnostic(ErrorCode.ERR_NoSuchMember, "Run").WithArguments("System.Threading.Tasks.Task", "Run").WithLocation(10, 25),
// (10,14): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'.
// if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false))
Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)").WithLocation(10, 14),
// (6,54): warning CS0649: Field 'TestDataPointBase.integrationService' is never assigned to, and will always have its default value null
// private readonly IVisualStudioIntegrationService integrationService;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "integrationService").WithArguments("TestDataPointBase.integrationService", "null").WithLocation(6, 54)
);
}
[Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
public void Bug960755_01()
{
var source = @"
using System.Collections.Generic;
class C
{
static void M(IList<C> c)
{
var tmp = new C();
tmp.M((a, b) => c.Add);
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body;
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Null(symbolInfo.Symbol);
Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
}
[Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
public void Bug960755_02()
{
var source = @"
using System.Collections.Generic;
class C
{
static void M(IList<C> c)
{
int tmp = c.Add;
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer.Value;
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Null(symbolInfo.Symbol);
Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString());
Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason);
}
[Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")]
public void Bug960755_03()
{
var source = @"
using System.Collections.Generic;
class C
{
static void M(IList<C> c)
{
var tmp = new C();
tmp.M((a, b) => c.Add);
}
static void M(System.Func<int, int, System.Action<C>> x)
{}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
var model = comp.GetSemanticModel(tree);
var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body;
var symbolInfo = model.GetSymbolInfo(expr);
Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal(0, symbolInfo.CandidateSymbols.Length);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact]
public void RefLambdaInferenceMethodArgument()
{
var text = @"
delegate ref int D();
class C
{
static void MD(D d) { }
static int i = 0;
static void M()
{
MD(() => ref i);
MD(() => { return ref i; });
MD(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefLambdaInferenceDelegateCreation()
{
var text = @"
delegate ref int D();
class C
{
static int i = 0;
static void M()
{
var d = new D(() => ref i);
d = new D(() => { return ref i; });
d = new D(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefLambdaInferenceOverloadedDelegateType()
{
var text = @"
delegate ref int D();
delegate int E();
class C
{
static void M(D d) { }
static void M(E e) { }
static int i = 0;
static void M()
{
M(() => ref i);
M(() => { return ref i; });
M(delegate { return ref i; });
M(() => i);
M(() => { return i; });
M(delegate { return i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics();
}
[Fact]
public void RefLambdaInferenceArgumentBadRefReturn()
{
var text = @"
delegate int E();
class C
{
static void ME(E e) { }
static int i = 0;
static void M()
{
ME(() => ref i);
ME(() => { return ref i; });
ME(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (11,22): error CS8149: By-reference returns may only be used in by-reference returning methods.
// ME(() => ref i);
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(11, 22),
// (12,20): error CS8149: By-reference returns may only be used in by-reference returning methods.
// ME(() => { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(12, 20),
// (13,23): error CS8149: By-reference returns may only be used in by-reference returning methods.
// ME(delegate { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(13, 23));
}
[Fact]
public void RefLambdaInferenceDelegateCreationBadRefReturn()
{
var text = @"
delegate int E();
class C
{
static int i = 0;
static void M()
{
var e = new E(() => ref i);
e = new E(() => { return ref i; });
e = new E(delegate { return ref i; });
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (9,33): error CS8149: By-reference returns may only be used in by-reference returning methods.
// var e = new E(() => ref i);
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(9, 33),
// (10,27): error CS8149: By-reference returns may only be used in by-reference returning methods.
// e = new E(() => { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(10, 27),
// (11,30): error CS8149: By-reference returns may only be used in by-reference returning methods.
// e = new E(delegate { return ref i; });
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(11, 30));
}
[Fact]
public void RefLambdaInferenceMixedByValueAndByRefReturns()
{
var text = @"
delegate ref int D();
delegate int E();
class C
{
static void MD(D e) { }
static void ME(E e) { }
static int i = 0;
static void M()
{
MD(() => {
if (i == 0)
{
return ref i;
}
return i;
});
ME(() => {
if (i == 0)
{
return ref i;
}
return i;
});
}
}
";
CreateCompilationWithMscorlib45(text).VerifyDiagnostics(
// (18,13): error CS8150: By-value returns may only be used in by-value returning methods.
// return i;
Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(18, 13),
// (23,17): error CS8149: By-reference returns may only be used in by-reference returning methods.
// return ref i;
Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(23, 17));
}
[WorkItem(1112875, "DevDiv")]
[WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")]
[Fact]
public void Bug1112875_1()
{
var comp = CreateCompilation(@"
using System;
class Program
{
static void Main()
{
ICloneable c = """";
Goo(() => (c.Clone()), null);
}
static void Goo(Action x, string y) { }
static void Goo(Func<object> x, object y) { Console.WriteLine(42); }
}", options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "42");
}
[WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")]
[Fact]
public void Bug1112875_2()
{
var comp = CreateCompilation(@"
class Program
{
void M()
{
var d = new System.Action(() => (new object()));
}
}
");
comp.VerifyDiagnostics(
// (6,41): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// var d = new System.Action(() => (new object()));
Diagnostic(ErrorCode.ERR_IllegalStatement, "(new object())").WithLocation(6, 41));
}
[WorkItem(1830, "https://github.com/dotnet/roslyn/issues/1830")]
[Fact]
public void FuncOfVoid()
{
var comp = CreateCompilation(@"
using System;
class Program
{
void M1<T>(Func<T> f) {}
void Main(string[] args)
{
M1(() => { return System.Console.Beep(); });
}
}
");
comp.VerifyDiagnostics(
// (8,27): error CS4029: Cannot return an expression of type 'void'
// M1(() => { return System.Console.Beep(); });
Diagnostic(ErrorCode.ERR_CantReturnVoid, "System.Console.Beep()").WithLocation(8, 27)
);
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_01()
{
var src = @"
using System;
class Program
{
static Func<Program, string> stuff()
{
return a => a.
}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,23): error CS1001: Identifier expected
// return a => a.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 23),
// (8,23): error CS1002: ; expected
// return a => a.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 23)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_02()
{
var src = @"
using System;
class Program
{
static void stuff()
{
Func<Program, string> l = a => a.
}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,42): error CS1001: Identifier expected
// Func<Program, string> l = a => a.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 42),
// (8,42): error CS1002: ; expected
// Func<Program, string> l = a => a.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 42)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_03()
{
var src = @"
using System;
class Program
{
static void stuff()
{
M1(a => a.);
}
static void M1(Func<Program, string> l){}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,20): error CS1001: Identifier expected
// M1(a => a.);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 20)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")]
public void ParameterReference_04()
{
var src = @"
using System;
class Program
{
static void stuff()
{
var l = (Func<Program, string>) (a => a.);
}
}
";
var compilation = CreateCompilation(src);
compilation.VerifyDiagnostics(
// (8,49): error CS1001: Identifier expected
// var l = (Func<Program, string>) (a => a.);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 49)
);
var tree = compilation.SyntaxTrees.Single();
var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single();
Assert.Equal("a.", node.Parent.ToString().Trim());
var semanticModel = compilation.GetSemanticModel(tree);
var symbolInfo = semanticModel.GetSymbolInfo(node);
Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString());
}
[Fact]
[WorkItem(3826, "https://github.com/dotnet/roslyn/issues/3826")]
public void ExpressionTreeSelfAssignmentShouldError()
{
var source = @"
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<int, int>> x = y => y = y;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (9,45): warning CS1717: Assignment made to same variable; did you mean to assign something else?
// Expression<Func<int, int>> x = y => y = y;
Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y = y").WithLocation(9, 45),
// (9,45): error CS0832: An expression tree may not contain an assignment operator
// Expression<Func<int, int>> x = y => y = y;
Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "y = y").WithLocation(9, 45));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2(default(Struct1)));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2(default(Struct1)));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default(Struct1)").WithArguments("Struct1").WithLocation(8, 40));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructDefaultExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2(default));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2(default));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 40));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructDefaultCastExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2((Struct1) default));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,50): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2((Struct1) default));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("Struct1").WithLocation(8, 50));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructNewExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method((Class1 c) => c.Method2(new Struct1()));
}
public void Method2(Struct1 s1) { }
public static void Method<T>(Expression<Action<T>> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,40): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Class1 c) => c.Method2(new Struct1()));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "new Struct1()").WithArguments("Struct1").WithLocation(8, 40));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructParamExpressionTree()
{
var text = @"
using System.Linq.Expressions;
public delegate void Delegate1(Struct1 s);
public class Class1
{
public void Method1()
{
Method((Struct1 s) => Method2());
}
public void Method2() { }
public static void Method(Expression<Delegate1> expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (9,25): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'Struct1'.
// Method((Struct1 s) => Method2());
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "s").WithArguments("Struct1").WithLocation(9, 25));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void RefStructParamLambda()
{
var text = @"
public delegate void Delegate1(Struct1 s);
public class Class1
{
public void Method1()
{
Method((Struct1 s) => Method2());
}
public void Method2() { }
public static void Method(Delegate1 expression) { }
}
public ref struct Struct1 { }
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics();
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void TypedReferenceExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public class Class1
{
public void Method1()
{
Method(() => Method2(default));
}
public void Method2(TypedReference tr) { }
public static void Method(Expression<Action> expression) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (8,30): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'.
// Method(() => Method2(default));
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "default").WithArguments("TypedReference").WithLocation(8, 30));
}
[Fact, WorkItem(30776, "https://github.com/dotnet/roslyn/issues/30776")]
public void TypedReferenceParamExpressionTree()
{
var text = @"
using System;
using System.Linq.Expressions;
public delegate void Delegate1(TypedReference tr);
public class Class1
{
public void Method1()
{
Method((TypedReference tr) => Method2());
}
public void Method2() { }
public static void Method(Expression<Delegate1> expression) { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(text).VerifyDiagnostics(
// (9,32): error CS8640: Expression tree cannot contain value of ref struct or restricted type 'TypedReference'.
// Method((TypedReference tr) => Method2());
Diagnostic(ErrorCode.ERR_ExpressionTreeCantContainRefStruct, "tr").WithArguments("TypedReference").WithLocation(9, 32));
}
[Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")]
public void ReturnInferenceCache_Dynamic_vs_Object_01()
{
var source =
@"
using System;
using System.Collections;
using System.Collections.Generic;
public static class Program
{
public static void Main(string[] args)
{
IEnumerable<dynamic> dynX = null;
// CS1061 'object' does not contain a definition for 'Text'...
// tooltip on 'var' shows IColumn instead of IEnumerable<dynamic>
var result = dynX.Select(_ => _.Text);
}
public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector)
{
throw new NotImplementedException();
}
public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector)
{
System.Console.WriteLine(""Select<T, S>"");
return null;
}
}
public interface IColumn { }
";
var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: "Select<T, S>");
}
[Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")]
public void ReturnInferenceCache_Dynamic_vs_Object_02()
{
var source =
@"
using System;
using System.Collections;
using System.Collections.Generic;
public static class Program
{
public static void Main(string[] args)
{
IEnumerable<dynamic> dynX = null;
// CS1061 'object' does not contain a definition for 'Text'...
// tooltip on 'var' shows IColumn instead of IEnumerable<dynamic>
var result = dynX.Select(_ => _.Text);
}
public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector)
{
System.Console.WriteLine(""Select<T, S>"");
return null;
}
public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector)
{
throw new NotImplementedException();
}
}
public interface IColumn { }
";
var compilation = CreateCompilation(source, new[] { CSharpRef }, options: TestOptions.ReleaseExe);
CompileAndVerify(compilation, expectedOutput: "Select<T, S>");
}
[Fact, WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void SyntaxAndSemanticErrorInLambda()
{
var source =
@"
using System;
class C
{
public static void Main(string[] args)
{
Action a = () => { new X().ToString() };
a();
}
}
";
CreateCompilation(source).VerifyDiagnostics(
// (7,47): error CS1002: ; expected
// Action a = () => { new X().ToString() };
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 47),
// (7,32): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?)
// Action a = () => { new X().ToString() };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(7, 32)
);
}
[Fact, WorkItem(4527, "https://github.com/dotnet/roslyn/issues/4527")]
public void AnonymousMethodExpressionWithoutParameterList()
{
var source =
@"
using System;
using System.Threading.Tasks;
namespace RoslynAsyncDelegate
{
class Program
{
static EventHandler MyEvent;
static void Main(string[] args)
{
MyEvent += async delegate { await Task.Delay(0); };
}
}
}
";
var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AnonymousMethodExpression)).Single();
Assert.Equal("async delegate { await Task.Delay(0); }", node1.ToString());
Assert.Equal("void System.EventHandler.Invoke(System.Object sender, System.EventArgs e)", model.GetTypeInfo(node1).ConvertedType.GetMembers("Invoke").Single().ToTestDisplayString());
var lambdaParameters = ((IMethodSymbol)(model.GetSymbolInfo(node1)).Symbol).Parameters;
Assert.Equal("System.Object <p0>", lambdaParameters[0].ToTestDisplayString());
Assert.Equal("System.EventArgs <p1>", lambdaParameters[1].ToTestDisplayString());
CompileAndVerify(compilation);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError01()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(() => { new Unbound1 }); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,58): error CS1526: A new expression requires (), [], or {} after type
// class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
Diagnostic(ErrorCode.ERR_BadNewExpr, "}").WithLocation(2, 58),
// (2,58): error CS1002: ; expected
// class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 58),
// (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?)
// class C { C() { string.Empty.Select(() => { new Unbound1 }); } }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError02()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,62): error CS1002: ; expected
// class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 62),
// (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?)
// class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError03()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,61): error CS1003: Syntax error, ',' expected
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_SyntaxError, "Unbound2").WithArguments(",", "").WithLocation(2, 61),
// (2,52): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52),
// (2,61): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 61),
// (2,42): error CS0103: The name 'Unbound1' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError04()
{
var source =
@"using System.Linq;
class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,52): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52),
// (2,42): error CS0103: The name 'Unbound1' does not exist in the current context
// class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42)
);
}
[Fact]
[WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")]
public void TestLambdaWithError05()
{
var source =
@"using System.Linq;
class C { C() { Unbound2.Select(x => Unbound1); } }";
CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (2,17): error CS0103: The name 'Unbound2' does not exist in the current context
// class C { C() { Unbound2.Select(x => Unbound1); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 17),
// (2,38): error CS0103: The name 'Unbound1' does not exist in the current context
// class C { C() { Unbound2.Select(x => Unbound1); } }
Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 38)
);
}
[Fact]
[WorkItem(4480, "https://github.com/dotnet/roslyn/issues/4480")]
public void TestLambdaWithError06()
{
var source =
@"class Program
{
static void Main(string[] args)
{
// completion should work even in a syntactically invalid lambda
var handler = new MyDelegateType((s, e) => { e. });
}
}
public delegate void MyDelegateType(
object sender,
MyArgumentType e
);
public class MyArgumentType
{
public int SomePublicMember;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source)
.VerifyDiagnostics(
// var handler = new MyDelegateType((s, e) => { e. });
Diagnostic(ErrorCode.ERR_IdentifierExpected, "}").WithLocation(6, 57),
// (6,57): error CS1002: ; expected
// var handler = new MyDelegateType((s, e) => { e. });
Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(6, 57)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("e", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal("MyArgumentType", typeInfo.Type.Name);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.NotEmpty(typeInfo.Type.GetMembers("SomePublicMember"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError07()
{
var source =
@"using System;
using System.Collections.Generic;
public static class Program
{
public static void Main()
{
var parameter = new List<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public static class Enumerable
{
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue)
{
return default(TSource);
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource defaultValue)
{
return default(TSource);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError08()
{
var source =
@"using System;
using System.Collections.Generic;
public static class Program
{
public static void Main()
{
var parameter = new List<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public static class Enumerable
{
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, params TSource[] defaultValue)
{
return default(TSource);
}
public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, params TSource[] defaultValue)
{
return default(TSource);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (9,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError09()
{
var source =
@"using System;
public static class Program
{
public static void Main()
{
var parameter = new MyList<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public class MyList<TSource>
{
public TSource FirstOrDefault(TSource defaultValue)
{
return default(TSource);
}
public TSource FirstOrDefault(Func<TSource, bool> predicate, TSource defaultValue)
{
return default(TSource);
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (8,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
public void TestLambdaWithError10()
{
var source =
@"using System;
public static class Program
{
public static void Main()
{
var parameter = new MyList<string>();
var result = parameter.FirstOrDefault(x => x. );
}
}
public class MyList<TSource>
{
public TSource FirstOrDefault(params TSource[] defaultValue)
{
return default(TSource);
}
public TSource FirstOrDefault(Func<TSource, bool> predicate, params TSource[] defaultValue)
{
return default(TSource);
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics(
// (8,55): error CS1001: Identifier expected
// var result = parameter.FirstOrDefault(x => x. );
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55)
);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[Fact]
[WorkItem(557, "https://github.com/dotnet/roslyn/issues/557")]
public void TestLambdaWithError11()
{
var source =
@"using System.Linq;
public static class Program
{
public static void Main()
{
var x = new {
X = """".Select(c => c.
Y = 0,
};
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("c", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Struct, typeInfo.Type.TypeKind);
Assert.Equal("Char", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("IsHighSurrogate")); // check it is the char we know and love
}
[Fact]
[WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")]
public void TestLambdaWithError12()
{
var source =
@"using System.Linq;
class Program
{
static void Main(string[] args)
{
var z = args.Select(a => a.
var goo =
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First();
Assert.Equal("a", eReference.ToString());
var typeInfo = sm.GetTypeInfo(eReference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
[WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")]
[WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")]
[Fact]
public void TestLambdaWithError13()
{
// These tests ensure we attempt to perform type inference and bind a lambda expression
// argument even when there are too many or too few arguments to an invocation, in the
// case when there is more than one method in the method group.
// See https://github.com/dotnet/roslyn/issues/11901 for the case of one method in the group
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Thing<string> t = null;
t.X1(x => x, 1); // too many args
t.X2(x => x); // too few args
t.M2(string.Empty, x => x, 1); // too many args
t.M3(string.Empty, x => x); // too few args
}
}
public class Thing<T>
{
public void M2<T>(T x, Func<T, T> func) {}
public void M3<T>(T x, Func<T, T> func, T y) {}
// Ensure we have more than one method in the method group
public void M2() {}
public void M3() {}
}
public static class XThing
{
public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
// Ensure we have more than one method in the method group
public static void X1(this object self) {}
public static void X2(this object self) {}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")]
public void TestLambdaWithError15()
{
// These tests ensure we attempt to perform type inference and bind a lambda expression
// argument even when there are too many or too few arguments to an invocation, in the
// case when there is exactly one method in the method group.
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Thing<string> t = null;
t.X1(x => x, 1); // too many args
t.X2(x => x); // too few args
t.M2(string.Empty, x => x, 1); // too many args
t.M3(string.Empty, x => x); // too few args
}
}
public class Thing<T>
{
public void M2<T>(T x, Func<T, T> func) {}
public void M3<T>(T x, Func<T, T> func, T y) {}
}
public static class XThing
{
public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")]
public void TestLambdaWithError16()
{
// These tests ensure we use the substituted method to bind a lambda expression
// argument even when there are too many or too few arguments to an invocation, in the
// case when there is exactly one method in the method group.
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Thing<string> t = null;
t.X1<string>(x => x, 1); // too many args
t.X2<string>(x => x); // too few args
t.M2<string>(string.Empty, x => x, 1); // too many args
t.M3<string>(string.Empty, x => x); // too few args
}
}
public class Thing<T>
{
public void M2<T>(T x, Func<T, T> func) {}
public void M3<T>(T x, Func<T, T> func, T y) {}
}
public static class XThing
{
public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null;
public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null;
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
public void TestLambdaWithError17()
{
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Ma(action: (x, y) => x.ToString(), t: string.Empty);
Mb(action: (x, y) => x.ToString(), t: string.Empty);
}
static void Ma<T>(T t, Action<T, T, int> action) { }
static void Mb<T>(T t, Action<T, T, int> action) { }
static void Mb() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
public void TestLambdaWithError18()
{
var source =
@"using System;
class Program
{
static void Main(string[] args)
{
Ma(string.Empty, (x, y) => x.ToString());
Mb(string.Empty, (x, y) => x.ToString());
}
static void Ma<T>(T t, Action<T, T, int> action) { }
static void Mb<T>(T t, Action<T, T, int> action) { }
static void Mb() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
[Fact]
[WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")]
public void TestLambdaWithError19()
{
var source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void Main(string[] args)
{
Ma(string.Empty, (x, y) => x.ToString());
Mb(string.Empty, (x, y) => x.ToString());
Mc(string.Empty, (x, y) => x.ToString());
}
static void Ma<T>(T t, Expression<Action<T, T, int>> action) { }
static void Mb<T>(T t, Expression<Action<T, T, int>> action) { }
static void Mb<T>(T t, Action<T, T, int> action) { }
static void Mc<T>(T t, Expression<Action<T, T, int>> action) { }
static void Mc() { }
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>())
{
var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First();
Assert.Equal("x", reference.ToString());
var typeInfo = sm.GetTypeInfo(reference);
Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind);
Assert.Equal("String", typeInfo.Type.Name);
Assert.NotEmpty(typeInfo.Type.GetMembers("Replace"));
}
}
// See MaxParameterListsForErrorRecovery.
[Fact]
public void BuildArgumentsForErrorRecovery_ManyOverloads()
{
BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery - 1, tooMany: false);
BuildArgumentsForErrorRecovery_ManyOverloads_Internal(Binder.MaxParameterListsForErrorRecovery, tooMany: true);
}
private void BuildArgumentsForErrorRecovery_ManyOverloads_Internal(int n, bool tooMany)
{
var builder = new StringBuilder();
builder.AppendLine("using System;");
for (int i = 0; i < n; i++)
{
builder.AppendLine($"class C{i} {{ }}");
}
builder.Append(
@"class A { }
class B { }
class C
{
void M()
{
F(1, (t, a, b, c) => { });
var o = this[(a, b, c) => { }];
}
");
// Too few parameters.
AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, C{i}> a) {{ }}");
AppendLines(builder, n, i => $" object this[Action<A, C{i}> a] => {i}");
// Type inference failure.
AppendLines(builder, n, i => $" void F<T, U>(T t, Action<T, U, C{i}> a) where U : T {{ }}");
// Too many parameters.
AppendLines(builder, n, i => $" void F<T>(T t, Action<T, A, B, C, C{i}> a) {{ }}");
AppendLines(builder, n, i => $" object this[Action<A, B, C, C{i}> a] => {i}");
builder.AppendLine("}");
var source = builder.ToString();
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees[0];
var sm = compilation.GetSemanticModel(tree);
var lambdas = tree.GetRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().ToArray();
// F(1, (t, a, b, c) => { });
var lambda = lambdas[0];
var parameters = lambda.ParameterList.Parameters;
var parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]);
Assert.False(parameter.Type.IsErrorType());
Assert.Equal("System.Int32 t", parameter.ToTestDisplayString());
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[1]);
Assert.False(parameter.Type.IsErrorType());
Assert.Equal("A a", parameter.ToTestDisplayString());
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[3]);
Assert.Equal(tooMany, parameter.Type.IsErrorType());
Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString());
// var o = this[(a, b, c) => { }];
lambda = lambdas[1];
parameters = lambda.ParameterList.Parameters;
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[0]);
Assert.False(parameter.Type.IsErrorType());
Assert.Equal("A a", parameter.ToTestDisplayString());
parameter = (IParameterSymbol)sm.GetDeclaredSymbol(parameters[2]);
Assert.Equal(tooMany, parameter.Type.IsErrorType());
Assert.Equal(tooMany ? "? c" : "C c", parameter.ToTestDisplayString());
}
private static void AppendLines(StringBuilder builder, int n, Func<int, string> getLine)
{
for (int i = 0; i < n; i++)
{
builder.AppendLine(getLine(i));
}
}
[Fact]
[WorkItem(13797, "https://github.com/dotnet/roslyn/issues/13797")]
public void DelegateAsAction()
{
var source = @"
using System;
public static class C
{
public static void M() => Dispatch(delegate { });
public static T Dispatch<T>(Func<T> func) => default(T);
public static void Dispatch(Action func) { }
}";
var comp = CreateCompilation(source);
CompileAndVerify(comp);
}
[Fact, WorkItem(278481, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=278481")]
public void LambdaReturningNull_1()
{
var src = @"
public static class ExtensionMethods
{
public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Linq.IQueryable<TOuter> outerValues,
System.Linq.IQueryable<TInner> innerValues,
System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector,
System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector,
System.Collections.Generic.IEqualityComparer<TKey> comparer)
{ return null; }
public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Linq.IQueryable<TOuter> outerValues,
System.Linq.IQueryable<TInner> innerValues,
System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector,
System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector,
System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector)
{
System.Console.WriteLine(""1"");
return null;
}
public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Collections.Generic.IEnumerable<TOuter> outerValues,
System.Linq.IQueryable<TInner> innerValues,
System.Func<TOuter, TKey> outerKeySelector,
System.Func<TInner, TKey> innerKeySelector,
System.Func<TOuter, TInner, TResult> fullResultSelector,
System.Func<TOuter, TResult> partialResultSelector)
{
System.Console.WriteLine(""2"");
return null;
}
public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>(
this System.Collections.Generic.IEnumerable<TOuter> outerQueryable,
System.Collections.Generic.IEnumerable<TInner> innerQueryable,
System.Func<TOuter, TKey> outerKeySelector,
System.Func<TInner, TKey> innerKeySelector,
System.Func<TOuter, TInner, TResult> resultSelector)
{ return null; }
}
partial class C
{
public static void Main()
{
System.Linq.IQueryable<A> outerValue = null;
System.Linq.IQueryable<B> innerValues = null;
outerValue.LeftOuterJoin(innerValues,
co => co.id,
coa => coa.id,
(co, coa) => null,
co => co);
}
}
class A
{
public int id=2;
}
class B
{
public int id = 2;
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1");
}
[Fact, WorkItem(296550, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296550")]
public void LambdaReturningNull_2()
{
var src = @"
class Test1<T>
{
public void M1(System.Func<T> x) {}
public void M1<S>(System.Func<S> x) {}
public void M2<S>(System.Func<S> x) {}
public void M2(System.Func<T> x) {}
}
class Test2 : Test1<System.>
{
void Main()
{
M1(()=> null);
M2(()=> null);
}
}
";
var comp = CreateCompilation(src, options: TestOptions.DebugDll);
comp.VerifyDiagnostics(
// (10,32): error CS1001: Identifier expected
// class Test2 : Test1<System.>
Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(10, 32)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void LambdaSquigglesArea()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Action<bool>> x = x1 => x2 =>
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,58): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// System.Func<bool, System.Action<bool>> x = x1 => x2 =>
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "x2 =>").WithArguments("lambda expression").WithLocation(6, 58)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void LambdaSquigglesAreaInAsync()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,93): error CS4010: Cannot convert async lambda expression to delegate type 'Task<Action<bool>>'. An async lambda expression may return void, Task or Task<T>, none of which are convertible to 'Task<Action<bool>>'.
// System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
Diagnostic(ErrorCode.ERR_CantConvAsyncAnonFuncReturns, "x2 =>").WithArguments("lambda expression", "System.Threading.Tasks.Task<System.Action<bool>>").WithLocation(6, 93),
// (6,90): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// System.Func<bool, System.Threading.Tasks.Task<System.Action<bool>>> x = async x1 => x2 =>
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 90)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void DelegateSquigglesArea()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2)
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,58): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// System.Func<bool, System.Action<bool>> x = x1 => delegate(bool x2)
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate(bool x2)").WithArguments("lambda expression").WithLocation(6, 58)
);
}
[Fact, WorkItem(22662, "https://github.com/dotnet/roslyn/issues/22662")]
public void DelegateWithoutArgumentsSquigglesArea()
{
var src = @"
class C
{
void M()
{
System.Func<bool, System.Action> x = x1 => delegate
{
error();
};
}
}
";
var comp = CreateCompilation(src);
comp.VerifyDiagnostics(
// (8,13): error CS0103: The name 'error' does not exist in the current context
// error();
Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 13),
// (6,52): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type
// System.Func<bool, System.Action> x = x1 => delegate
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "delegate").WithArguments("lambda expression").WithLocation(6, 52)
);
}
[Fact]
public void ThrowExpression_Lambda()
{
var src = @"using System;
class C
{
public static void Main()
{
Action a = () => throw new Exception(""1"");
try
{
a();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
Func<int, int> b = x => throw new Exception(""2"");
try
{
b(0);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
b = (int x) => throw new Exception(""3"");
try
{
b(0);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
b = (x) => throw new Exception(""4"");
try
{
b(0);
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
}";
var comp = CreateCompilationWithMscorlib40AndSystemCore(src, options: TestOptions.DebugExe);
CompileAndVerify(comp, expectedOutput: "1234");
}
[Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
public void InMalformedEmbeddedStatement_01()
{
var source = @"
class Program
{
void method1()
{
if (method2())
.Any(b => b.ContentType, out var chars)
{
}
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single();
var model = comp.GetSemanticModel(tree);
Assert.Equal("ContentType", contentType.ToString());
Assert.Null(model.GetSymbolInfo(contentType).Symbol);
Assert.Equal(TypeKind.Error, model.GetTypeInfo(contentType).Type.TypeKind);
ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single();
model = comp.GetSemanticModel(tree);
Assert.Equal("b", b.ToString());
ISymbol symbol = model.GetSymbolInfo(b).Symbol;
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.Equal("? b", symbol.ToTestDisplayString());
Assert.Equal(TypeKind.Error, model.GetTypeInfo(b).Type.TypeKind);
ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
model = comp.GetSemanticModel(tree);
symbol = model.GetDeclaredSymbol(parameterSyntax);
Assert.Equal(SymbolKind.Parameter, symbol.Kind);
Assert.Equal("? b", symbol.ToTestDisplayString());
}
[Fact, WorkItem(23883, "https://github.com/dotnet/roslyn/issues/23883")]
public void InMalformedEmbeddedStatement_02()
{
var source = @"
class Program
{
void method1()
{
if (method2())
.Any(b => b.ContentType, out var chars)
{
}
}
}
";
var tree = SyntaxFactory.ParseSyntaxTree(source);
var comp = CreateCompilation(tree);
ExpressionSyntax contentType = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "ContentType").Single();
var model = comp.GetSemanticModel(tree);
Assert.Equal("ContentType", contentType.ToString());
var lambda = (IMethodSymbol)model.GetEnclosingSymbol(contentType.SpanStart);
Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind);
ExpressionSyntax b = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "b").Single();
model = comp.GetSemanticModel(tree);
Assert.Equal("b", b.ToString());
lambda = (IMethodSymbol)model.GetEnclosingSymbol(b.SpanStart);
Assert.Equal(MethodKind.AnonymousFunction, lambda.MethodKind);
model = comp.GetSemanticModel(tree);
ParameterSyntax parameterSyntax = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParameterSyntax>().Single();
Assert.Equal("void Program.method1()", model.GetEnclosingSymbol(parameterSyntax.SpanStart).ToTestDisplayString());
}
[Fact]
public void ShadowNames_Local()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M()
{
Action a1 = () => { object x = 0; }; // local
Action<string> a2 = x => { }; // parameter
Action<string> a3 = (string x) => { }; // parameter
object x = null;
Action a4 = () => { void x() { } }; // method
Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = () => { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36),
// (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = x => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29),
// (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a3 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
// (13,34): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a4 = () => { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(13, 34),
// (14,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(14, 38));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Parameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static Action<object> F = (object x) =>
{
Action a1 = () => { object x = 0; }; // local
Action<string> a2 = x => { }; // parameter
Action<string> a3 = (string x) => { }; // parameter
Action a4 = () => { void x() { } }; // method
Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
};
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,36): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = () => { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 36),
// (10,29): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = x => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 29),
// (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a3 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
// (13,38): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 38));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_TypeParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M<x>()
{
Action a1 = () => { object x = 0; }; // local
Action<string> a2 = x => { }; // parameter
Action<string> a3 = (string x) => { }; // parameter
Action a4 = () => { void x() { } }; // method
Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,36): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a1 = () => { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 36),
// (10,29): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> a2 = x => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 29),
// (11,37): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> a3 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 37),
// (12,34): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a4 = () => { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(12, 34),
// (13,38): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
// Action a5 = () => { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(13, 38));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_QueryParameter()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
_ = from x in args select (Action)(() => { object x = 0; }); // local
_ = from x in args select (Action<string>)(x => { }); // parameter
_ = from x in args select (Action<string>)((string x) => { }); // parameter
_ = from x in args select (Action)(() => { void x() { } }); // method
_ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,59): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// _ = from x in args select (Action)(() => { object x = 0; }); // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 59),
// (10,52): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// _ = from x in args select (Action<string>)(x => { }); // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 52),
// (11,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// _ = from x in args select (Action<string>)((string x) => { }); // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 60),
// (13,61): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// _ = from x in args select (Action)(() => { _ = from x in new[] { 1, 2, 3 } select x; }); // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 61));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Local_Delegate()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M()
{
object x = null;
Action a1 = delegate() { object x = 0; }; // local
Action<string> a2 = delegate(string x) { }; // parameter
Action a3 = delegate() { void x() { } }; // method
Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (10,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = delegate() { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 41),
// (11,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = delegate(string x) { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 45),
// (12,39): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a3 = delegate() { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(12, 39),
// (13,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(13, 43));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular8);
comp.VerifyDiagnostics();
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Parameter_Delegate()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static Action<object> F = (object x) =>
{
Action a1 = delegate() { object x = 0; }; // local
Action<string> a2 = delegate(string x) { }; // parameter
Action a3 = delegate() { void x() { } }; // method
Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
};
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = delegate() { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(9, 41),
// (10,45): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> a2 = delegate(string x) { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 45),
// (12,43): error CS1931: The range variable 'x' conflicts with a previous declaration of 'x'
// Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableOverrides, "x").WithArguments("x").WithLocation(12, 43));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_TypeParameter_Delegate()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
using System.Linq;
class Program
{
static void M<x>()
{
Action a1 = delegate() { object x = 0; }; // local
Action<string> a2 = delegate(string x) { }; // parameter
Action a3 = delegate() { void x() { } }; // method
Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (9,41): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a1 = delegate() { object x = 0; }; // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(9, 41),
// (10,45): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> a2 = delegate(string x) { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(10, 45),
// (11,39): error CS0412: 'x': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a3 = delegate() { void x() { } }; // method
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "x").WithArguments("x").WithLocation(11, 39),
// (12,43): error CS1948: The range variable 'x' cannot have the same name as a method type parameter
// Action a4 = delegate() { _ = from x in new[] { 1, 2, 3 } select x; }; // range variable
Diagnostic(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, "x").WithArguments("x").WithLocation(12, 43));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LambdaInsideLambda()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M<T>(object x)
{
Action a1 = () =>
{
Action b1 = () => { object x = 1; }; // local
Action<string> b2 = (string x) => { }; // parameter
};
Action a2 = () =>
{
Action b3 = () => { object T = 3; }; // local
Action<string> b4 = T => { }; // parameter
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (10,40): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action b1 = () => { object x = 1; }; // local
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(10, 40),
// (11,41): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<string> b2 = (string x) => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 41),
// (15,40): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action b3 = () => { object T = 3; }; // local
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 40),
// (16,33): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<string> b4 = T => { }; // parameter
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(16, 33));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Underscore_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, Func<int, int>> f = _ => _ => _;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,44): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, Func<int, int>> f = _ => _ => _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 44));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Underscore_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, int, int> f = (_, _) => 0;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,37): error CS8370: Feature 'lambda discard parameters' is not available in C# 7.3. Please use language version 9.0 or greater.
// Func<int, int, int> f = (_, _) => 0;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "_").WithArguments("lambda discard parameters", "9.0").WithLocation(8, 37));
comp = CreateCompilation(source);
comp.VerifyEmitDiagnostics();
}
[Fact]
public void ShadowNames_Nested_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,55): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 55),
// (8,60): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, Func<int, Func<int, int>>> f = x => x => x => x;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 60));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_Nested_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (8,87): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(8, 87),
// (8,94): error CS0136: A local or parameter named 'y' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "y").WithArguments("y").WithLocation(8, 94),
// (8,97): error CS0136: A local or parameter named '_' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Func<int, int, int, Func<int, int, Func<int, int, int>>> f = (x, y, z) => (_, x) => (y, _) => x + y + z + _;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "_").WithArguments("_").WithLocation(8, 97));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LambdaInsideLocalFunction_01()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M()
{
void F1()
{
object x = null;
Action a1 = () => { int x = 0; };
}
void F2<T>()
{
Action a2 = () => { int T = 0; };
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (11,37): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action a1 = () => { int x = 0; };
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 37),
// (15,37): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action a2 = () => { int T = 0; };
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(15, 37));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void ShadowNames_LambdaInsideLocalFunction_02()
{
var source =
@"#pragma warning disable 0219
#pragma warning disable 8321
using System;
class Program
{
static void M<T>()
{
object x = null;
void F()
{
Action<int> a1 = (int x) =>
{
Action b1 = () => { int T = 0; };
};
Action a2 = () =>
{
int x = 0;
Action<int> b2 = (int T) => { };
};
}
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3);
comp.VerifyDiagnostics(
// (11,35): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// Action<int> a1 = (int x) =>
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(11, 35),
// (13,41): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action b1 = () => { int T = 0; };
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(13, 41),
// (17,21): error CS0136: A local or parameter named 'x' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x = 0;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x").WithArguments("x").WithLocation(17, 21),
// (18,39): error CS0412: 'T': a parameter, local variable, or local function cannot have the same name as a method type parameter
// Action<int> b2 = (int T) => { };
Diagnostic(ErrorCode.ERR_LocalSameNameAsTypeParam, "T").WithArguments("T").WithLocation(18, 39));
comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaAttributes_01()
{
var sourceA =
@"using System;
class A : Attribute { }
class B : Attribute { }
partial class Program
{
static Delegate D1() => (Action)([A] () => { });
static Delegate D2(int x) => (Func<int, int, int>)((int y, [A][B] int z) => x);
static Delegate D3() => (Action<int, object>)(([A]_, y) => { });
Delegate D4() => (Func<int>)([return: A][B] () => GetHashCode());
}";
var sourceB =
@"using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
partial class Program
{
static string GetAttributeString(object a)
{
return a.GetType().FullName;
}
static void Report(Delegate d)
{
var m = d.Method;
var forMethod = ToString(""method"", m.GetCustomAttributes(inherit: false));
var forReturn = ToString(""return"", m.ReturnTypeCustomAttributes.GetCustomAttributes(inherit: false));
var forParameters = ToString(""parameter"", m.GetParameters().SelectMany(p => p.GetCustomAttributes(inherit: false)));
Console.WriteLine(""{0}:{1}{2}{3}"", m.Name, forMethod, forReturn, forParameters);
}
static string ToString(string target, IEnumerable<object> attributes)
{
var builder = new StringBuilder();
foreach (var attribute in attributes)
builder.Append($"" [{target}: {attribute}]"");
return builder.ToString();
}
static void Main()
{
Report(D1());
Report(D2(0));
Report(D3());
Report(new Program().D4());
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.Regular10, options: TestOptions.ReleaseExe);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>();
var pairs = exprs.Select(e => (e, model.GetSymbolInfo(e).Symbol)).ToArray();
var expectedAttributes = new[]
{
"[A] () => { }: [method: A]",
"(int y, [A][B] int z) => x: [parameter: A] [parameter: B]",
"([A]_, y) => { }: [parameter: A]",
"[return: A][B] () => GetHashCode(): [method: B] [return: A]",
};
AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesInternal(p.Item1, p.Item2)));
AssertEx.Equal(expectedAttributes, pairs.Select(p => getAttributesPublic(p.Item1, p.Item2)));
CompileAndVerify(comp, expectedOutput:
@"<D1>b__0_0: [method: A]
<D2>b__0: [parameter: A] [parameter: B]
<D3>b__2_0: [parameter: A]
<D4>b__3_0: [method: System.Runtime.CompilerServices.CompilerGeneratedAttribute] [method: B] [return: A]");
static string getAttributesInternal(LambdaExpressionSyntax expr, ISymbol symbol)
{
var method = symbol.GetSymbol<MethodSymbol>();
return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes()));
}
static string getAttributesPublic(LambdaExpressionSyntax expr, ISymbol symbol)
{
var method = (IMethodSymbol)symbol;
return format(expr, method.GetAttributes(), method.GetReturnTypeAttributes(), method.Parameters.SelectMany(p => p.GetAttributes()));
}
static string format(LambdaExpressionSyntax expr, IEnumerable<object> methodAttributes, IEnumerable<object> returnAttributes, IEnumerable<object> parameterAttributes)
{
var forMethod = toString("method", methodAttributes);
var forReturn = toString("return", returnAttributes);
var forParameters = toString("parameter", parameterAttributes);
return $"{expr}:{forMethod}{forReturn}{forParameters}";
}
static string toString(string target, IEnumerable<object> attributes)
{
var builder = new StringBuilder();
foreach (var attribute in attributes)
builder.Append($" [{target}: {attribute}]");
return builder.ToString();
}
}
[Fact]
public void LambdaAttributes_02()
{
var source =
@"using System;
class AAttribute : Attribute { }
class BAttribute : Attribute { }
class C
{
static void Main()
{
Action<object, object> a;
a = [A, B] (x, y) => { };
a = ([A] x, [B] y) => { };
a = (object x, [A][B] object y) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (9,13): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = [A, B] (x, y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A, B]").WithArguments("lambda attributes", "10.0").WithLocation(9, 13),
// (10,14): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = ([A] x, [B] y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(10, 14),
// (10,21): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = ([A] x, [B] y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(10, 21),
// (11,24): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = (object x, [A][B] object y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[A]").WithArguments("lambda attributes", "10.0").WithLocation(11, 24),
// (11,27): error CS8773: Feature 'lambda attributes' is not available in C# 9.0. Please use language version 10.0 or greater.
// a = (object x, [A][B] object y) => { };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "[B]").WithArguments("lambda attributes", "10.0").WithLocation(11, 27));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaAttributes_03()
{
var source =
@"using System;
class AAttribute : Attribute { }
class BAttribute : Attribute { }
class C
{
static void Main()
{
Action<object, object> a = delegate (object x, [A][B] object y) { };
Func<object, object> f = [A][B] x => x;
}
}";
var expectedDiagnostics = new[]
{
// (8,56): error CS7014: Attributes are not valid in this context.
// Action<object, object> a = delegate (object x, [A][B] object y) { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[A]").WithLocation(8, 56),
// (8,59): error CS7014: Attributes are not valid in this context.
// Action<object, object> a = delegate (object x, [A][B] object y) { };
Diagnostic(ErrorCode.ERR_AttributesNotAllowed, "[B]").WithLocation(8, 59),
// (9,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list.
// Func<object, object> f = [A][B] x => x;
Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[A]").WithLocation(9, 34),
// (9,37): error CS8916: Attributes on lambda expressions require a parenthesized parameter list.
// Func<object, object> f = [A][B] x => x;
Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[B]").WithLocation(9, 37)
};
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(expectedDiagnostics);
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics(expectedDiagnostics);
}
[Fact]
public void LambdaAttributes_04()
{
var sourceA =
@"namespace N1
{
class A1Attribute : System.Attribute { }
}
namespace N2
{
class A2Attribute : System.Attribute { }
}";
var sourceB =
@"using N1;
using N2;
class Program
{
static void Main()
{
System.Action a1 = [A1] () => { };
System.Action<object> a2 = ([A2] object obj) => { };
}
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaAttributes_05()
{
var source =
@"class Program
{
static void Main()
{
System.Action a1 = [A1] () => { };
System.Func<object> a2 = [return: A2] () => null;
System.Action<object> a3 = ([A3] object obj) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,29): error CS0246: The type or namespace name 'A1Attribute' could not be found (are you missing a using directive or an assembly reference?)
// System.Action a1 = [A1] () => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1Attribute").WithLocation(5, 29),
// (5,29): error CS0246: The type or namespace name 'A1' could not be found (are you missing a using directive or an assembly reference?)
// System.Action a1 = [A1] () => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A1").WithArguments("A1").WithLocation(5, 29),
// (6,43): error CS0246: The type or namespace name 'A2Attribute' could not be found (are you missing a using directive or an assembly reference?)
// System.Func<object> a2 = [return: A2] () => null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2Attribute").WithLocation(6, 43),
// (6,43): error CS0246: The type or namespace name 'A2' could not be found (are you missing a using directive or an assembly reference?)
// System.Func<object> a2 = [return: A2] () => null;
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A2").WithArguments("A2").WithLocation(6, 43),
// (7,38): error CS0246: The type or namespace name 'A3Attribute' could not be found (are you missing a using directive or an assembly reference?)
// System.Action<object> a3 = ([A3] object obj) => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3Attribute").WithLocation(7, 38),
// (7,38): error CS0246: The type or namespace name 'A3' could not be found (are you missing a using directive or an assembly reference?)
// System.Action<object> a3 = ([A3] object obj) => { };
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A3").WithArguments("A3").WithLocation(7, 38));
}
[Fact]
public void LambdaAttributes_06()
{
var source =
@"using System;
class AAttribute : Attribute
{
public AAttribute(Action a) { }
}
[A([B] () => { })]
class BAttribute : Attribute
{
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,2): error CS0181: Attribute constructor parameter 'a' has type 'Action', which is not a valid attribute parameter type
// [A([B] () => { })]
Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("a", "System.Action").WithLocation(6, 2));
}
[Fact]
public void LambdaAttributes_BadAttributeLocation()
{
var source =
@"using System;
[AttributeUsage(AttributeTargets.Property)]
class PropAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
class MethodAttribute : Attribute { }
[AttributeUsage(AttributeTargets.ReturnValue)]
class ReturnAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Parameter)]
class ParamAttribute : Attribute { }
[AttributeUsage(AttributeTargets.GenericParameter)]
class TypeParamAttribute : Attribute { }
class Program
{
static void Main()
{
Action<object> a =
[Prop] // 1
[Return] // 2
[Method]
[return: Prop] // 3
[return: Return]
[return: Method] // 4
(
[Param]
[TypeParam] // 5
object o) =>
{
};
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (23,14): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [Prop] // 1
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(23, 14),
// (24,14): error CS0592: Attribute 'Return' is not valid on this declaration type. It is only valid on 'return' declarations.
// [Return] // 2
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Return").WithArguments("Return", "return").WithLocation(24, 14),
// (26,22): error CS0592: Attribute 'Prop' is not valid on this declaration type. It is only valid on 'property, indexer' declarations.
// [return: Prop] // 3
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Prop").WithArguments("Prop", "property, indexer").WithLocation(26, 22),
// (28,22): error CS0592: Attribute 'Method' is not valid on this declaration type. It is only valid on 'method' declarations.
// [return: Method] // 4
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "Method").WithArguments("Method", "method").WithLocation(28, 22),
// (31,14): error CS0592: Attribute 'TypeParam' is not valid on this declaration type. It is only valid on 'type parameter' declarations.
// [TypeParam] // 5
Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "TypeParam").WithArguments("TypeParam", "type parameter").WithLocation(31, 14));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var lambda = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var symbol = (IMethodSymbol)model.GetSymbolInfo(lambda).Symbol;
Assert.NotNull(symbol);
verifyAttributes(symbol.GetAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute");
verifyAttributes(symbol.GetReturnTypeAttributes(), "PropAttribute", "ReturnAttribute", "MethodAttribute");
verifyAttributes(symbol.Parameters[0].GetAttributes(), "ParamAttribute", "TypeParamAttribute");
void verifyAttributes(ImmutableArray<AttributeData> attributes, params string[] expectedAttributeNames)
{
var actualAttributes = attributes.SelectAsArray(a => a.AttributeClass.GetSymbol());
var expectedAttributes = expectedAttributeNames.Select(n => comp.GetTypeByMetadataName(n));
AssertEx.Equal(expectedAttributes, actualAttributes);
}
}
[Fact]
public void LambdaAttributes_AttributeSemanticModel()
{
var source =
@"using System;
class AAttribute : Attribute { }
class BAttribute : Attribute { }
class CAttribute : Attribute { }
class DAttribute : Attribute { }
class Program
{
static void Main()
{
Action a = [A] () => { };
Func<object> b = [return: B] () => null;
Action<object> c = ([C] object obj) => { };
Func<object, object> d = [D] x => x;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (13,34): error CS8916: Attributes on lambda expressions require a parenthesized parameter list.
// Func<object, object> d = [D] x => x;
Diagnostic(ErrorCode.ERR_AttributesRequireParenthesizedLambdaExpression, "[D]").WithLocation(13, 34));
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var attributeSyntaxes = tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>();
var actualAttributes = attributeSyntaxes.Select(a => model.GetSymbolInfo(a).Symbol.GetSymbol<MethodSymbol>()).ToImmutableArray();
var expectedAttributes = new[] { "AAttribute", "BAttribute", "CAttribute", "DAttribute" }.Select(a => comp.GetTypeByMetadataName(a).InstanceConstructors.Single()).ToImmutableArray();
AssertEx.Equal(expectedAttributes, actualAttributes);
}
[Theory]
[InlineData("Action a = [A] () => { };")]
[InlineData("Func<object> f = [return: A] () => null;")]
[InlineData("Action<int> a = ([A] int i) => { };")]
public void LambdaAttributes_SpeculativeSemanticModel(string statement)
{
string source =
$@"using System;
class AAttribute : Attribute {{ }}
class Program
{{
static void Main()
{{
{statement}
}}
}}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.Single();
var model = comp.GetSemanticModel(tree);
var a = (IdentifierNameSyntax)tree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name;
Assert.Equal("A", a.Identifier.Text);
var attrInfo = model.GetSymbolInfo(a);
var attrType = comp.GetMember<NamedTypeSymbol>("AAttribute").GetPublicSymbol();
var attrCtor = attrType.GetMember(".ctor");
Assert.Equal(attrCtor, attrInfo.Symbol);
// Assert that this is also true for the speculative semantic model
var newTree = SyntaxFactory.ParseSyntaxTree(source + " ");
var m = newTree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single();
Assert.True(model.TryGetSpeculativeSemanticModelForMethodBody(m.Body.SpanStart, m, out model));
a = (IdentifierNameSyntax)newTree.GetRoot().DescendantNodes().OfType<AttributeSyntax>().Single().Name;
Assert.Equal("A", a.Identifier.Text);
// If we aren't using the right binder here, the compiler crashes going through the binder factory
var info = model.GetSymbolInfo(a);
// This behavior is wrong. See https://github.com/dotnet/roslyn/issues/24135
Assert.Equal(attrType, info.Symbol);
}
[Fact]
public void LambdaAttributes_DisallowedAttributes()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
namespace System.Runtime.CompilerServices
{
public class IsReadOnlyAttribute : Attribute { }
public class IsUnmanagedAttribute : Attribute { }
public class IsByRefLikeAttribute : Attribute { }
public class NullableContextAttribute : Attribute { public NullableContextAttribute(byte b) { } }
}
class Program
{
static void Main()
{
Action a =
[IsReadOnly] // 1
[IsUnmanaged] // 2
[IsByRefLike] // 3
[Extension] // 4
[NullableContext(0)] // 5
() => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (15,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsReadOnlyAttribute'. This is reserved for compiler usage.
// [IsReadOnly] // 1
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsReadOnly").WithArguments("System.Runtime.CompilerServices.IsReadOnlyAttribute").WithLocation(15, 14),
// (16,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsUnmanagedAttribute'. This is reserved for compiler usage.
// [IsUnmanaged] // 2
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsUnmanaged").WithArguments("System.Runtime.CompilerServices.IsUnmanagedAttribute").WithLocation(16, 14),
// (17,14): error CS8335: Do not use 'System.Runtime.CompilerServices.IsByRefLikeAttribute'. This is reserved for compiler usage.
// [IsByRefLike] // 3
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "IsByRefLike").WithArguments("System.Runtime.CompilerServices.IsByRefLikeAttribute").WithLocation(17, 14),
// (18,14): error CS1112: Do not use 'System.Runtime.CompilerServices.ExtensionAttribute'. Use the 'this' keyword instead.
// [Extension] // 4
Diagnostic(ErrorCode.ERR_ExplicitExtension, "Extension").WithLocation(18, 14),
// (19,14): error CS8335: Do not use 'System.Runtime.CompilerServices.NullableContextAttribute'. This is reserved for compiler usage.
// [NullableContext(0)] // 5
Diagnostic(ErrorCode.ERR_ExplicitReservedAttr, "NullableContext(0)").WithArguments("System.Runtime.CompilerServices.NullableContextAttribute").WithLocation(19, 14));
}
[Fact]
public void LambdaAttributes_DisallowedSecurityAttributes()
{
var source =
@"using System;
using System.Security;
class Program
{
static void Main()
{
Action a =
[SecurityCritical] // 1
[SecuritySafeCriticalAttribute] // 2
async () => { }; // 3
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,14): error CS4030: Security attribute 'SecurityCritical' cannot be applied to an Async method.
// [SecurityCritical] // 1
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecurityCritical").WithArguments("SecurityCritical").WithLocation(8, 14),
// (9,14): error CS4030: Security attribute 'SecuritySafeCriticalAttribute' cannot be applied to an Async method.
// [SecuritySafeCriticalAttribute] // 2
Diagnostic(ErrorCode.ERR_SecurityCriticalOrSecuritySafeCriticalOnAsync, "SecuritySafeCriticalAttribute").WithArguments("SecuritySafeCriticalAttribute").WithLocation(9, 14),
// (10,22): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// async () => { }; // 3
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(10, 22));
}
[Fact]
public void LambdaAttributes_ObsoleteAttribute()
{
var source =
@"using System;
class Program
{
static void Report(Action a)
{
foreach (var attribute in a.Method.GetCustomAttributes(inherit: false))
Console.Write(attribute);
}
static void Main()
{
Report([Obsolete] () => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe);
CompileAndVerify(comp, expectedOutput: "System.ObsoleteAttribute");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var symbol = model.GetSymbolInfo(expr).Symbol;
Assert.Equal("System.ObsoleteAttribute", symbol.GetAttributes().Single().ToString());
}
[Fact]
public void LambdaParameterAttributes_Conditional()
{
var source =
@"using System;
using System.Diagnostics;
class Program
{
static void Report(Action a)
{
}
static void Main()
{
Report([Conditional(""DEBUG"")] static () => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview, options: TestOptions.ReleaseExe);
comp.VerifyDiagnostics(
// (10,17): error CS0577: The Conditional attribute is not valid on 'lambda expression' because it is a constructor, destructor, operator, lambda expression, or explicit interface implementation
// Report([Conditional("DEBUG")] static () => { });
Diagnostic(ErrorCode.ERR_ConditionalOnSpecialMethod, @"Conditional(""DEBUG"")").WithArguments("lambda expression").WithLocation(10, 17));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single();
Assert.Equal(new[] { "DEBUG" }, lambda.GetAppliedConditionalSymbols());
}
[Fact]
public void LambdaAttributes_WellKnownAttributes()
{
var sourceA =
@"using System;
using System.Runtime.InteropServices;
using System.Security;
class Program
{
static void Main()
{
Action a1 = [DllImport(""MyModule.dll"")] static () => { };
Action a2 = [DynamicSecurityMethod] () => { };
Action a3 = [SuppressUnmanagedCodeSecurity] () => { };
Func<object> a4 = [return: MarshalAs((short)0)] () => null;
}
}";
var sourceB =
@"namespace System.Security
{
internal class DynamicSecurityMethodAttribute : Attribute { }
}";
var comp = CreateCompilation(new[] { sourceA, sourceB }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,22): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern'
// Action a1 = [DllImport("MyModule.dll")] static () => { };
Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport").WithLocation(8, 22));
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(4, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Null(lambdas[0].GetDllImportData()); // [DllImport] is ignored if there are errors.
Assert.True(lambdas[1].RequiresSecurityObject);
Assert.True(lambdas[2].HasDeclarativeSecurity);
Assert.Equal(default, lambdas[3].ReturnValueMarshallingInformation.UnmanagedType);
}
[Fact]
public void LambdaAttributes_Permissions()
{
var source =
@"#pragma warning disable 618
using System;
using System.Security.Permissions;
class Program
{
static void Main()
{
Action a1 = [PermissionSet(SecurityAction.Deny)] () => { };
}
}";
var comp = CreateCompilationWithMscorlib40(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single();
Assert.NotEmpty(lambda.GetSecurityInformation());
}
[Fact]
public void LambdaAttributes_NullableAttributes_01()
{
var source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Func<object> a1 = [return: MaybeNull][return: NotNull] () => null;
Func<object, object> a2 = [return: NotNullIfNotNull(""obj"")] (object obj) => obj;
Func<bool> a4 = [MemberNotNull(""x"")][MemberNotNullWhen(false, ""y"")][MemberNotNullWhen(true, ""z"")] () => true;
}
}";
var comp = CreateCompilation(
new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition, NotNullIfNotNullAttributeDefinition, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition },
parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(3, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Equal(FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull, lambdas[0].ReturnTypeFlowAnalysisAnnotations);
Assert.Equal(new[] { "obj" }, lambdas[1].ReturnNotNullIfParameterNotNull);
Assert.Equal(new[] { "x" }, lambdas[2].NotNullMembers);
Assert.Equal(new[] { "y" }, lambdas[2].NotNullWhenFalseMembers);
Assert.Equal(new[] { "z" }, lambdas[2].NotNullWhenTrueMembers);
}
[Fact]
public void LambdaAttributes_NullableAttributes_02()
{
var source =
@"#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Func<object> a1 = [return: MaybeNull] () => null;
Func<object?> a2 = [return: NotNull] () => null;
}
}";
var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition, NotNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Report WRN_NullReferenceReturn for a2, not for a1.
comp.VerifyDiagnostics(
// (8,53): warning CS8603: Possible null reference return.
// Func<object> a1 = [return: MaybeNull] () => null;
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 53));
}
[Fact]
public void LambdaAttributes_NullableAttributes_03()
{
var source =
@"#nullable enable
using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Action<object> a1 = ([AllowNull] x) => { x.ToString(); };
Action<object?> a2 = ([DisallowNull] x) => { x.ToString(); };
}
}";
var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Report nullability mismatch warning assigning lambda to a2.
comp.VerifyDiagnostics(
// (8,50): warning CS8602: Dereference of a possibly null reference.
// Action<object> a1 = ([AllowNull] x) => { x.ToString(); };
Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 50));
}
[WorkItem(55013, "https://github.com/dotnet/roslyn/issues/55013")]
[Fact]
public void NullableTypeArraySwitchPattern()
{
var source =
@"#nullable enable
class C
{
object? field;
string Prop => field switch
{
string?[] a => ""a""
};
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (4,13): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null
// object? field;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(4, 13),
// (5,26): warning CS8509: The switch expression does not handle all possible values of its input type (it is not exhaustive). For example, the pattern '_' is not covered.
// string Prop => field switch
Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustive, "switch").WithArguments("_").WithLocation(5, 26));
}
[Fact]
public void LambdaAttributes_DoesNotReturn()
{
var source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Action a1 = [DoesNotReturn] () => { };
Action a2 = [DoesNotReturn] () => throw new Exception();
}
}";
var comp = CreateCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Report warning that lambda expression in a1 initializer returns.
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(2, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[0].FlowAnalysisAnnotations);
Assert.Equal(FlowAnalysisAnnotations.DoesNotReturn, lambdas[1].FlowAnalysisAnnotations);
}
[Fact]
public void LambdaAttributes_UnmanagedCallersOnly()
{
var source =
@"using System;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
Action a = [UnmanagedCallersOnly] static () => { };
}
}";
var comp = CreateCompilation(new[] { source, UnmanagedCallersOnlyAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,21): error CS8896: 'UnmanagedCallersOnly' can only be applied to ordinary static non-abstract methods or static local functions.
// Action a = [UnmanagedCallersOnly] static () => { };
Diagnostic(ErrorCode.ERR_UnmanagedCallersOnlyRequiresStatic, "UnmanagedCallersOnly").WithLocation(7, 21));
}
[Fact]
public void LambdaParameterAttributes_OptionalAndDefaultValueAttributes()
{
var source =
@"using System;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
Action<int> a1 = ([Optional, DefaultParameterValue(2)] int i) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
var lambda = exprs.SelectAsArray(e => GetLambdaSymbol(model, e)).Single();
var parameter = (SourceParameterSymbol)lambda.Parameters[0];
Assert.True(parameter.HasOptionalAttribute);
Assert.False(parameter.HasExplicitDefaultValue);
Assert.Equal(2, parameter.DefaultValueFromAttributes.Value);
}
[ConditionalFact(typeof(DesktopOnly))]
public void LambdaParameterAttributes_WellKnownAttributes()
{
var source =
@"using System;
using System.Runtime.CompilerServices;
class Program
{
static void Main()
{
Action<object> a1 = ([IDispatchConstant] object obj) => { };
Action<object> a2 = ([IUnknownConstant] object obj) => { };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(2, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.True(lambdas[0].Parameters[0].IsIDispatchConstant);
Assert.True(lambdas[1].Parameters[0].IsIUnknownConstant);
}
[Fact]
public void LambdaParameterAttributes_NullableAttributes_01()
{
var source =
@"using System;
using System.Diagnostics.CodeAnalysis;
class Program
{
static void Main()
{
Action<object> a1 = ([AllowNull][MaybeNullWhen(false)] object obj) => { };
Action<object, object> a2 = (object x, [NotNullIfNotNull(""x"")] object y) => { };
}
}";
var comp = CreateCompilation(
new[] { source, AllowNullAttributeDefinition, MaybeNullWhenAttributeDefinition, NotNullIfNotNullAttributeDefinition },
parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var exprs = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().ToImmutableArray();
Assert.Equal(2, exprs.Length);
var lambdas = exprs.SelectAsArray(e => GetLambdaSymbol(model, e));
Assert.Equal(FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.MaybeNullWhenFalse, lambdas[0].Parameters[0].FlowAnalysisAnnotations);
Assert.Equal(new[] { "x" }, lambdas[1].Parameters[1].NotNullIfParameterNotNull);
}
[Fact]
public void LambdaParameterAttributes_NullableAttributes_02()
{
var source =
@"#nullable enable
using System.Diagnostics.CodeAnalysis;
delegate bool D(out object? obj);
class Program
{
static void Main()
{
D d = ([NotNullWhen(true)] out object? obj) =>
{
obj = null;
return true;
};
}
}";
var comp = CreateCompilation(new[] { source, NotNullWhenAttributeDefinition }, parseOptions: TestOptions.RegularPreview);
// https://github.com/dotnet/roslyn/issues/52827: Should report WRN_ParameterConditionallyDisallowsNull.
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var expr = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single();
var lambda = GetLambdaSymbol(model, expr);
Assert.Equal(FlowAnalysisAnnotations.NotNullWhenTrue, lambda.Parameters[0].FlowAnalysisAnnotations);
}
[Fact]
public void LambdaReturnType_01()
{
var source =
@"using System;
class Program
{
static void F<T>()
{
Func<T> f1 = T () => default;
Func<T, T> f2 = T (x) => { return x; };
Func<T, T> f3 = T (T x) => x;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9);
comp.VerifyDiagnostics(
// (6,22): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater.
// Func<T> f1 = T () => default;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(6, 22),
// (7,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater.
// Func<T, T> f2 = T (x) => { return x; };
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(7, 25),
// (8,25): error CS8773: Feature 'lambda return type' is not available in C# 9.0. Please use language version 10.0 or greater.
// Func<T, T> f3 = T (T x) => x;
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "T").WithArguments("lambda return type", "10.0").WithLocation(8, 25));
comp = CreateCompilation(source, parseOptions: TestOptions.Regular10);
comp.VerifyDiagnostics();
}
[Fact]
public void LambdaReturnType_02()
{
var source =
@"using System;
class Program
{
static void F<T, U>()
{
Func<T> f1;
Func<U> f2;
f1 = T () => default;
f2 = T () => default;
f1 = U () => default;
f2 = U () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type
// f2 = T () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14),
// (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type
// f1 = U () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14));
}
[Fact]
public void LambdaReturnType_03()
{
var source =
@"using System;
class Program
{
static void F<T, U>() where U : T
{
Func<T> f1;
Func<U> f2;
f1 = T () => default;
f2 = T () => default;
f1 = U () => default;
f2 = U () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,14): error CS8934: Cannot convert lambda expression to type 'Func<U>' because the return type does not match the delegate return type
// f2 = T () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Func<U>").WithLocation(9, 14),
// (10,14): error CS8934: Cannot convert lambda expression to type 'Func<T>' because the return type does not match the delegate return type
// f1 = U () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Func<T>").WithLocation(10, 14));
}
[Fact]
public void LambdaReturnType_04()
{
var source =
@"using System;
using System.Linq.Expressions;
class Program
{
static void F<T, U>()
{
Expression<Func<T>> e1;
Expression<Func<U>> e2;
e1 = T () => default;
e2 = T () => default;
e1 = U () => default;
e2 = U () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<U>>' because the return type does not match the delegate return type
// e2 = T () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<U>>").WithLocation(10, 14),
// (11,14): error CS8934: Cannot convert lambda expression to type 'Expression<Func<T>>' because the return type does not match the delegate return type
// e1 = U () => default;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "U () => default").WithArguments("lambda expression", "System.Linq.Expressions.Expression<System.Func<T>>").WithLocation(11, 14));
}
[Fact]
public void LambdaReturnType_05()
{
var source =
@"#nullable enable
using System;
class Program
{
static void Main()
{
Func<dynamic> f1 = object () => default!;
Func<(int, int)> f2 = (int X, int Y) () => default;
Func<string?> f3 = string () => default!;
Func<IntPtr> f4 = nint () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes).
// Func<string?> f3 = string () => default!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => default!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28));
}
[Fact]
public void LambdaReturnType_06()
{
var source =
@"#nullable enable
using System;
using System.Linq.Expressions;
class Program
{
static void Main()
{
Expression<Func<object>> e1 = dynamic () => default!;
Expression<Func<(int X, int Y)>> e2 = (int, int) () => default;
Expression<Func<string>> e3 = string? () => default;
Expression<Func<nint>> e4 = IntPtr () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,39): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes).
// Expression<Func<string>> e3 = string? () => default;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => default").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 39));
}
[Fact]
public void LambdaReturnType_07()
{
var source =
@"#nullable enable
using System;
struct S<T> { }
class Program
{
static void Main()
{
Delegate d1 = string? () => default;
Delegate d2 = string () => default;
Delegate d3 = S<object?> () => default(S<object?>);
Delegate d4 = S<object?> () => default(S<object>);
Delegate d5 = S<object> () => default(S<object?>);
Delegate d6 = S<object> () => default(S<object>);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,36): warning CS8603: Possible null reference return.
// Delegate d2 = string () => default;
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(9, 36),
// (11,40): warning CS8619: Nullability of reference types in value of type 'S<object>' doesn't match target type 'S<object?>'.
// Delegate d4 = S<object?> () => default(S<object>);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object>)").WithArguments("S<object>", "S<object?>").WithLocation(11, 40),
// (12,39): warning CS8619: Nullability of reference types in value of type 'S<object?>' doesn't match target type 'S<object>'.
// Delegate d5 = S<object> () => default(S<object?>);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "default(S<object?>)").WithArguments("S<object?>", "S<object>").WithLocation(12, 39));
}
[Fact]
public void LambdaReturnType_08()
{
var source =
@"#nullable enable
using System;
struct S<T> { }
class Program
{
static void Main()
{
Func<string?> f1 = string? () => throw null!;
Func<string?> f2 = string () => throw null!;
Func<string> f3 = string? () => throw null!;
Func<string> f4 = string () => throw null!;
Func<S<object?>> f5 = S<object?> () => throw null!;
Func<S<object?>> f6 = S<object> () => throw null!;
Func<S<object>> f7 = S<object?> () => throw null!;
Func<S<object>> f8 = S<object> () => throw null!;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (9,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes).
// Func<string?> f2 = string () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => throw null!").WithArguments("lambda expression", "System.Func<string?>").WithLocation(9, 28),
// (10,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes).
// Func<string> f3 = string? () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => throw null!").WithArguments("lambda expression", "System.Func<string>").WithLocation(10, 27),
// (13,31): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object?>>' (possibly because of nullability attributes).
// Func<S<object?>> f6 = S<object> () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object> () => throw null!").WithArguments("lambda expression", "System.Func<S<object?>>").WithLocation(13, 31),
// (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<S<object>>' (possibly because of nullability attributes).
// Func<S<object>> f7 = S<object?> () => throw null!;
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "S<object?> () => throw null!").WithArguments("lambda expression", "System.Func<S<object>>").WithLocation(14, 30));
}
[Fact]
public void LambdaReturnType_09()
{
var source =
@"#nullable enable
struct S<T> { }
delegate ref T D1<T>();
delegate ref readonly T D2<T>();
class Program
{
static void Main()
{
D1<S<object?>> f1 = (ref S<object?> () => throw null!);
D1<S<object?>> f2 = (ref S<object> () => throw null!);
D1<S<object>> f3 = (ref S<object?> () => throw null!);
D1<S<object>> f4 = (ref S<object> () => throw null!);
D2<S<object?>> f5 = (ref readonly S<object?> () => throw null!);
D2<S<object?>> f6 = (ref readonly S<object> () => throw null!);
D2<S<object>> f7 = (ref readonly S<object?> () => throw null!);
D2<S<object>> f8 = (ref readonly S<object> () => throw null!);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object?>>' (possibly because of nullability attributes).
// D1<S<object?>> f2 = (ref S<object> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object> () => throw null!").WithArguments("lambda expression", "D1<S<object?>>").WithLocation(10, 30),
// (11,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D1<S<object>>' (possibly because of nullability attributes).
// D1<S<object>> f3 = (ref S<object?> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref S<object?> () => throw null!").WithArguments("lambda expression", "D1<S<object>>").WithLocation(11, 29),
// (14,30): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object?>>' (possibly because of nullability attributes).
// D2<S<object?>> f6 = (ref readonly S<object> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object> () => throw null!").WithArguments("lambda expression", "D2<S<object?>>").WithLocation(14, 30),
// (15,29): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'D2<S<object>>' (possibly because of nullability attributes).
// D2<S<object>> f7 = (ref readonly S<object?> () => throw null!);
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "ref readonly S<object?> () => throw null!").WithArguments("lambda expression", "D2<S<object>>").WithLocation(15, 29));
}
[Fact]
public void LambdaReturnType_10()
{
var source =
@"delegate T D1<T>(ref T t);
delegate ref T D2<T>(ref T t);
delegate ref readonly T D3<T>(ref T t);
class Program
{
static void F<T>()
{
D1<T> d1;
D2<T> d2;
D3<T> d3;
d1 = T (ref T t) => t;
d2 = T (ref T t) => t;
d3 = T (ref T t) => t;
d1 = (ref T (ref T t) => ref t);
d2 = (ref T (ref T t) => ref t);
d3 = (ref T (ref T t) => ref t);
d1 = (ref readonly T (ref T t) => ref t);
d2 = (ref readonly T (ref T t) => ref t);
d3 = (ref readonly T (ref T t) => ref t);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (12,14): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type
// d2 = T (ref T t) => t;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D2<T>").WithLocation(12, 14),
// (13,14): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type
// d3 = T (ref T t) => t;
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "T (ref T t) => t").WithArguments("lambda expression", "D3<T>").WithLocation(13, 14),
// (14,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type
// d1 = (ref T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(14, 15),
// (16,15): error CS8934: Cannot convert lambda expression to type 'D3<T>' because the return type does not match the delegate return type
// d3 = (ref T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref T (ref T t) => ref t").WithArguments("lambda expression", "D3<T>").WithLocation(16, 15),
// (17,15): error CS8934: Cannot convert lambda expression to type 'D1<T>' because the return type does not match the delegate return type
// d1 = (ref readonly T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D1<T>").WithLocation(17, 15),
// (18,15): error CS8934: Cannot convert lambda expression to type 'D2<T>' because the return type does not match the delegate return type
// d2 = (ref readonly T (ref T t) => ref t);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "ref readonly T (ref T t) => ref t").WithArguments("lambda expression", "D2<T>").WithLocation(18, 15));
}
[Fact]
public void LambdaReturnType_11()
{
var source =
@"using System;
class Program
{
static void Main()
{
Delegate d;
d = (ref void () => { });
d = (ref readonly void () => { });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,14): error CS8917: The delegate type could not be inferred.
// d = (ref void () => { });
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref void () => { }").WithLocation(7, 14),
// (7,18): error CS1547: Keyword 'void' cannot be used in this context
// d = (ref void () => { });
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(7, 18),
// (8,14): error CS8917: The delegate type could not be inferred.
// d = (ref readonly void () => { });
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ref readonly void () => { }").WithLocation(8, 14),
// (8,27): error CS1547: Keyword 'void' cannot be used in this context
// d = (ref readonly void () => { });
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(8, 27));
}
[WorkItem(55217, "https://github.com/dotnet/roslyn/issues/55217")]
[ConditionalFact(typeof(DesktopOnly))]
public void LambdaReturnType_12()
{
var source =
@"using System;
class Program
{
static void Main()
{
Delegate d;
d = TypedReference () => throw null;
d = RuntimeArgumentHandle () => throw null;
d = ArgIterator () => throw null;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'TypedReference'
// d = TypedReference () => throw null;
Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "TypedReference").WithArguments("System.TypedReference").WithLocation(7, 13),
// (7,13): error CS8917: The delegate type could not be inferred.
// d = TypedReference () => throw null;
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "TypedReference () => throw null").WithLocation(7, 13),
// (8,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'RuntimeArgumentHandle'
// d = RuntimeArgumentHandle () => throw null;
Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "RuntimeArgumentHandle").WithArguments("System.RuntimeArgumentHandle").WithLocation(8, 13),
// (8,13): error CS8917: The delegate type could not be inferred.
// d = RuntimeArgumentHandle () => throw null;
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "RuntimeArgumentHandle () => throw null").WithLocation(8, 13),
// (9,13): error CS1599: The return type of a method, delegate, or function pointer cannot be 'ArgIterator'
// d = ArgIterator () => throw null;
Diagnostic(ErrorCode.ERR_MethodReturnCantBeRefAny, "ArgIterator").WithArguments("System.ArgIterator").WithLocation(9, 13),
// (9,13): error CS8917: The delegate type could not be inferred.
// d = ArgIterator () => throw null;
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "ArgIterator () => throw null").WithLocation(9, 13));
}
[Fact]
public void LambdaReturnType_13()
{
var source =
@"static class S { }
delegate S D();
class Program
{
static void Main()
{
D d = S () => default;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,15): error CS0722: 'S': static types cannot be used as return types
// D d = S () => default;
Diagnostic(ErrorCode.ERR_ReturnTypeIsStaticClass, "S").WithArguments("S").WithLocation(7, 15));
}
[Fact]
public void LambdaReturnType_14()
{
var source =
@"using System;
class Program
{
static void Main()
{
Delegate d = async int () => 0;
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (6,35): error CS1983: The return type of an async method must be void, Task, Task<T>, a task-like type, IAsyncEnumerable<T>, or IAsyncEnumerator<T>
// Delegate d = async int () => 0;
Diagnostic(ErrorCode.ERR_BadAsyncReturn, "=>").WithLocation(6, 35),
// (6,35): warning CS1998: This async method lacks 'await' operators and will run synchronously. Consider using the 'await' operator to await non-blocking API calls, or 'await Task.Run(...)' to do CPU-bound work on a background thread.
// Delegate d = async int () => 0;
Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "=>").WithLocation(6, 35));
}
[Fact]
public void LambdaReturnType_15()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate ref Task D(string s);
class Program
{
static void Main()
{
Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,23): error CS8917: The delegate type could not be inferred.
// Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "async ref Task (s) => { _ = s.Length; await Task.Yield(); }").WithLocation(8, 23),
// (8,29): error CS1073: Unexpected token 'ref'
// Delegate d1 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29),
// (9,22): error CS1073: Unexpected token 'ref'
// D d2 = async ref Task (s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22));
}
[Fact]
public void LambdaReturnType_16()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate ref Task D(string s);
class Program
{
static void Main()
{
Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,29): error CS1073: Unexpected token 'ref'
// Delegate d1 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(8, 29),
// (9,22): error CS1073: Unexpected token 'ref'
// D d2 = async ref Task (string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_UnexpectedToken, "ref").WithArguments("ref").WithLocation(9, 22));
}
[Fact]
public void LambdaReturnType_17()
{
var source =
@"#nullable enable
using System;
class Program
{
static void F(string? x, string y)
{
Func<string?> f1 = string () => { if (x is null) return x; return y; };
Func<string> f2 = string? () => { if (x is not null) return x; return y; };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,28): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string?>' (possibly because of nullability attributes).
// Func<string?> f1 = string () => { if (x is null) return x; return y; };
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string () => { if (x is null) return x; return y; }").WithArguments("lambda expression", "System.Func<string?>").WithLocation(7, 28),
// (7,65): warning CS8603: Possible null reference return.
// Func<string?> f1 = string () => { if (x is null) return x; return y; };
Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(7, 65),
// (8,27): warning CS8621: Nullability of reference types in return type of 'lambda expression' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes).
// Func<string> f2 = string? () => { if (x is not null) return x; return y; };
Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "string? () => { if (x is not null) return x; return y; }").WithArguments("lambda expression", "System.Func<string>").WithLocation(8, 27));
}
[Fact]
public void LambdaReturnType_CustomModifiers_01()
{
var sourceA =
@".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { }
.method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) Invoke () runtime managed { }
.method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { }
.method public hidebysig newslot virtual instance int32 modopt([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { }
}";
var refA = CompileIL(sourceA);
var sourceB =
@"class Program
{
static void F(D d)
{
System.Console.WriteLine(d());
}
static void Main()
{
F(() => 1);
F(int () => 2);
}
}";
CompileAndVerify(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview, expectedOutput:
@"1
2");
}
[Fact]
public void LambdaReturnType_CustomModifiers_02()
{
var sourceA =
@".class public auto ansi sealed D extends [mscorlib]System.MulticastDelegate
{
.method public hidebysig specialname rtspecialname instance void .ctor (object 'object', native int 'method') runtime managed { }
.method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) Invoke () runtime managed { }
.method public hidebysig newslot virtual instance class [mscorlib]System.IAsyncResult BeginInvoke (class [mscorlib]System.AsyncCallback callback, object 'object') runtime managed { }
.method public hidebysig newslot virtual instance int32 modreq([mscorlib]System.Int16) EndInvoke (class [mscorlib]System.IAsyncResult result) runtime managed { }
}";
var refA = CompileIL(sourceA);
var sourceB =
@"class Program
{
static void F(D d)
{
System.Console.WriteLine(d());
}
static void Main()
{
F(() => 1);
F(int () => 2);
}
}";
var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (5,34): error CS0570: 'D.Invoke()' is not supported by the language
// System.Console.WriteLine(d());
Diagnostic(ErrorCode.ERR_BindToBogus, "d()").WithArguments("D.Invoke()").WithLocation(5, 34),
// (9,11): error CS0570: 'D.Invoke()' is not supported by the language
// F(() => 1);
Diagnostic(ErrorCode.ERR_BindToBogus, "() => 1").WithArguments("D.Invoke()").WithLocation(9, 11),
// (10,11): error CS0570: 'D.Invoke()' is not supported by the language
// F(int () => 2);
Diagnostic(ErrorCode.ERR_BindToBogus, "int () => 2").WithArguments("D.Invoke()").WithLocation(10, 11));
}
[Fact]
public void LambdaReturnType_UseSiteErrors()
{
var sourceA =
@".class public sealed A extends [mscorlib]System.Object
{
.custom instance void [mscorlib]System.Runtime.CompilerServices.RequiredAttributeAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 FF 00 00 )
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret }
}";
var refA = CompileIL(sourceA);
var sourceB =
@"using System;
class B
{
static void F<T>(Func<T> f) { }
static void Main()
{
F(A () => default);
}
}";
var comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (7,11): error CS0648: 'A' is a type not supported by the language
// F(A () => default);
Diagnostic(ErrorCode.ERR_BogusType, "A").WithArguments("A").WithLocation(7, 11));
}
[Fact]
public void AsyncLambdaParameters_01()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate Task D(ref string s);
class Program
{
static void Main()
{
Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (8,41): error CS1988: Async methods cannot have ref, in or out parameters
// Delegate d1 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(8, 41),
// (9,34): error CS1988: Async methods cannot have ref, in or out parameters
// D d2 = async (ref string s) => { _ = s.Length; await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadAsyncArgType, "s").WithLocation(9, 34));
}
[ConditionalFact(typeof(DesktopOnly))]
public void AsyncLambdaParameters_02()
{
var source =
@"using System;
using System.Threading.Tasks;
delegate void D1(TypedReference r);
delegate void D2(RuntimeArgumentHandle h);
delegate void D3(ArgIterator i);
class Program
{
static void Main()
{
D1 d1 = async (TypedReference r) => { await Task.Yield(); };
D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); };
D3 d3 = async (ArgIterator i) => { await Task.Yield(); };
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,39): error CS4012: Parameters or locals of type 'TypedReference' cannot be declared in async methods or async lambda expressions.
// D1 d1 = async (TypedReference r) => { await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "r").WithArguments("System.TypedReference").WithLocation(10, 39),
// (11,46): error CS4012: Parameters or locals of type 'RuntimeArgumentHandle' cannot be declared in async methods or async lambda expressions.
// D2 d2 = async (RuntimeArgumentHandle h) => { await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "h").WithArguments("System.RuntimeArgumentHandle").WithLocation(11, 46),
// (12,36): error CS4012: Parameters or locals of type 'ArgIterator' cannot be declared in async methods or async lambda expressions.
// D3 d3 = async (ArgIterator i) => { await Task.Yield(); };
Diagnostic(ErrorCode.ERR_BadSpecialByRefLocal, "i").WithArguments("System.ArgIterator").WithLocation(12, 36));
}
[Fact]
public void BestType_01()
{
var source =
@"using System;
class A { }
class B1 : A { }
class B2 : A { }
interface I { }
class C1 : I { }
class C2 : I { }
class Program
{
static void F<T>(Func<bool, T> f) { }
static void Main()
{
F((bool b) => { if (b) return new B1(); return new B2(); });
F((bool b) => { if (b) return new C1(); return new C2(); });
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (13,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F((bool b) => { if (b) return new B1(); return new B2(); });
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(13, 9),
// (14,9): error CS0411: The type arguments for method 'Program.F<T>(Func<bool, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F((bool b) => { if (b) return new C1(); return new C2(); });
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<bool, T>)").WithLocation(14, 9));
}
// As above but with explicit return type.
[Fact]
public void BestType_02()
{
var source =
@"using System;
class A { }
class B1 : A { }
class B2 : A { }
interface I { }
class C1 : I { }
class C2 : I { }
class Program
{
static void F<T>(Func<bool, T> f) { Console.WriteLine(typeof(T)); }
static void Main()
{
F(A (bool b) => { if (b) return new B1(); return new B2(); });
F(I (bool b) => { if (b) return new C1(); return new C2(); });
}
}";
CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput:
@"A
I");
}
[Fact]
public void BestType_03()
{
var source =
@"using System;
class A { }
class B1 : A { }
class B2 : A { }
class Program
{
static void F<T>(Func<T> x, Func<T> y) { }
static void Main()
{
F(B2 () => null, B2 () => null);
F(A () => null, B2 () => null);
F(B1 () => null, B2 () => null);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (11,25): error CS8934: Cannot convert lambda expression to type 'Func<A>' because the return type does not match the delegate return type
// F(A () => null, B2 () => null);
Diagnostic(ErrorCode.ERR_CantConvAnonMethReturnType, "B2 () => null").WithArguments("lambda expression", "System.Func<A>").WithLocation(11, 25),
// (12,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T>, Func<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(B1 () => null, B2 () => null);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T>, System.Func<T>)").WithLocation(12, 9));
}
[Fact]
public void TypeInference_01()
{
var source =
@"using System;
class Program
{
static void F<T>(Func<object, T> f)
{
Console.WriteLine(typeof(T));
}
static void Main()
{
F(long (o) => 1);
}
}";
CompileAndVerify(source, parseOptions: TestOptions.RegularPreview, expectedOutput: @"System.Int64");
}
// Should method type inference make an explicit type inference
// from the lambda expression return type?
[Fact]
public void TypeInference_02()
{
var source =
@"using System;
class Program
{
static void F<T>(Func<T, T> f)
{
Console.WriteLine(typeof(T));
}
static void Main()
{
F(int (i) => i);
}
}";
var comp = CreateCompilation(source, parseOptions: TestOptions.RegularPreview);
comp.VerifyDiagnostics(
// (10,9): error CS0411: The type arguments for method 'Program.F<T>(Func<T, T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
// F(int (i) => i);
Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("Program.F<T>(System.Func<T, T>)").WithLocation(10, 9));
}
// CS4031 is not reported for async lambda in [SecurityCritical] type.
[Fact]
[WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")]
public void SecurityCritical_AsyncLambda()
{
var source =
@"using System;
using System.Security;
using System.Threading.Tasks;
[SecurityCritical]
class Program
{
static void Main()
{
Func<Task> f = async () => await Task.Yield();
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
// CS4031 is not reported for async lambda in [SecurityCritical] type.
[Fact]
[WorkItem(54074, "https://github.com/dotnet/roslyn/issues/54074")]
public void SecurityCritical_AsyncLambda_AttributeArgument()
{
var source =
@"using System;
using System.Security;
using System.Threading.Tasks;
class A : Attribute
{
internal A(int i) { }
}
[SecurityCritical]
[A(F(async () => await Task.Yield()))]
class Program
{
internal static int F(Func<Task> f) => 0;
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (9,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
// [A(F(async () => await Task.Yield()))]
Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F(async () => await Task.Yield())").WithLocation(9, 4));
}
private static LambdaSymbol GetLambdaSymbol(SemanticModel model, LambdaExpressionSyntax syntax)
{
return model.GetSymbolInfo(syntax).Symbol.GetSymbol<LambdaSymbol>();
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/VisualBasic/Portable/Symbols/AliasSymbol.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.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Symbol representing a using alias appearing in a compilation unit.
''' Generally speaking, these symbols do not appear in the set of symbols reachable
''' from the unnamed namespace declaration. In other words, when a using alias is used in a
''' program, it acts as a transparent alias, and the symbol to which it is an alias is used in
''' the symbol table. For example, in the source code
''' <pre>
''' Imports o = System.Object
''' Namespace NS
''' partial class C : Inherits o : End Class
''' partial class C : Inherits Object : End Class
''' partial class C : Inherits System.Object : End Class
''' End Namespace
'''
''' </pre>
''' all three declarations for class C are equivalent and result in the same symbol table object for C.
''' However, these alias symbols do appear in the results of certain SemanticModel APIs.
''' Specifically, for the base clause of the first of C's class declarations, the
''' following APIs may produce a result that contains an AliasSymbol:
''' <pre>
''' SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression);
''' SemanticInfo SemanticModel.BindExpression(SyntaxNode location, ExpressionSyntax expression);
''' SemanticInfo SemanticModel.BindType(SyntaxNode location, ExpressionSyntax type);
''' SemanticInfo SemanticModel.BindNamespaceOrType(SyntaxNode location, ExpressionSyntax type);
''' </pre>
''' Also, the following are affected if container=Nothing (and, for the latter, when container=Nothing or arity=0):
''' <pre>
''' Public Function LookupNames(position As Integer, Optional container As NamespaceOrTypeSymbol = Nothing, Optional options As LookupOptions = LookupOptions.Default, Optional results As List(Of String) = Nothing) As IList(Of String)
''' Public Function LookupSymbols(position As Integer,
''' Optional container As NamespaceOrTypeSymbol = Nothing,
''' Optional name As String = Nothing,
''' Optional arity As Integer? = Nothing,
''' Optional options As LookupOptions = LookupOptions.Default,
''' Optional results As List(Of Symbol) = Nothing) As IList(Of Symbol)
''' </pre>
''' </summary>
Friend NotInheritable Class AliasSymbol
Inherits Symbol
Implements IAliasSymbol
Private ReadOnly _aliasTarget As NamespaceOrTypeSymbol
Private ReadOnly _aliasName As String
Private ReadOnly _aliasLocations As ImmutableArray(Of Location)
Private ReadOnly _aliasContainer As Symbol
Friend Sub New(compilation As VisualBasicCompilation,
aliasContainer As Symbol,
aliasName As String,
aliasTarget As NamespaceOrTypeSymbol,
aliasLocation As Location)
Dim merged = TryCast(aliasContainer, MergedNamespaceSymbol)
Dim sourceNs As NamespaceSymbol = Nothing
If merged IsNot Nothing Then
sourceNs = merged.GetConstituentForCompilation(compilation)
End If
Me._aliasContainer = If(sourceNs, aliasContainer)
Me._aliasTarget = aliasTarget
Me._aliasName = aliasName
Me._aliasLocations = ImmutableArray.Create(aliasLocation)
End Sub
''' <summary>
''' The alias name.
''' </summary>
Public Overrides ReadOnly Property Name As String
Get
Return _aliasName
End Get
End Property
''' <summary>
''' Gets the kind of this symbol.
''' </summary>
''' <returns><see cref="SymbolKind.Alias"/></returns>
Public Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Alias
End Get
End Property
''' <summary>
''' Gets the <see cref="NamespaceOrTypeSymbol"/> for the
''' namespace or type referenced by the alias.
''' </summary>
Public ReadOnly Property Target As NamespaceOrTypeSymbol
Get
Return Me._aliasTarget
End Get
End Property
Private ReadOnly Property IAliasSymbol_Target As INamespaceOrTypeSymbol Implements IAliasSymbol.Target
Get
Return Target
End Get
End Property
''' <summary>
''' Gets the locations where this symbol was originally defined.
''' </summary>
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _aliasLocations
End Get
End Property
''' <summary>
''' Get the syntax node(s) where this symbol was declared in source.
''' </summary>
''' <returns>
''' The syntax node(s) that declared the symbol.
''' </returns>
''' <remarks>
''' To go the opposite direction (from syntax node to symbol), see <see cref="VBSemanticModel.GetDeclaredSymbol"/>.
''' </remarks>
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return GetDeclaringSyntaxReferenceHelper(Of SimpleImportsClauseSyntax)(Locations)
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members and was
''' also restricted from further overriding; i.e., declared with the "NotOverridable"
''' modifier. Never returns true for types.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared as requiring an override; i.e., declared
''' with the "MustOverride" modifier. Never returns true for types.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members; i.e., declared
''' with the "Overrides" modifier. Still returns true if the members was declared
''' to override something, but (erroneously) no member to override exists.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this member is overridable, has an implementation,
''' and does not override a base class member; i.e., declared with the "Overridable"
''' modifier. Does not return true for members declared as MustOverride or Overrides.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol is "shared"; i.e., declared with the "Shared"
''' modifier or implicitly always shared.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Get this accessibility that was declared on this symbol. For symbols that do
''' not have accessibility declared on them, returns NotApplicable.
''' </summary>
''' <returns><see cref="Accessibility.NotApplicable"/></returns>
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' Get the symbol that logically contains this symbol.
''' </summary>
''' <returns>
''' Using aliases in VB are always at the top
''' level within a compilation unit, within the [Global] namespace declaration. We
''' return that as the "containing" symbol, even though the alias isn't a member of the
''' namespace as such.
''' </returns>
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _aliasContainer
End Get
End Property
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
''' <param name="obj">
''' The object to compare with the current object.
''' </param>
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
ElseIf obj Is Nothing Then
Return False
End If
Dim other As AliasSymbol = TryCast(obj, AliasSymbol)
Return other IsNot Nothing AndAlso
Equals(Me.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) AndAlso
Me.ContainingAssembly Is other.ContainingAssembly
End Function
''' <summary>
''' Returns a hash code for the current object.
''' </summary>
Public Overrides Function GetHashCode() As Integer
Return If(Me.Locations.Length > 0, Me.Locations(0).GetHashCode(), Me.Name.GetHashCode())
End Function
Friend Overrides Function Accept(Of TArg, TResult)(visitor As VisualBasicSymbolVisitor(Of TArg, TResult), a As TArg) As TResult
Return visitor.VisitAlias(Me, a)
End Function
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitAlias(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitAlias(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitAlias(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitAlias(Me)
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.Generic
Imports System.Collections.Immutable
Imports System.Diagnostics
Imports System.Linq
Imports System.Threading
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' Symbol representing a using alias appearing in a compilation unit.
''' Generally speaking, these symbols do not appear in the set of symbols reachable
''' from the unnamed namespace declaration. In other words, when a using alias is used in a
''' program, it acts as a transparent alias, and the symbol to which it is an alias is used in
''' the symbol table. For example, in the source code
''' <pre>
''' Imports o = System.Object
''' Namespace NS
''' partial class C : Inherits o : End Class
''' partial class C : Inherits Object : End Class
''' partial class C : Inherits System.Object : End Class
''' End Namespace
'''
''' </pre>
''' all three declarations for class C are equivalent and result in the same symbol table object for C.
''' However, these alias symbols do appear in the results of certain SemanticModel APIs.
''' Specifically, for the base clause of the first of C's class declarations, the
''' following APIs may produce a result that contains an AliasSymbol:
''' <pre>
''' SemanticInfo SemanticModel.GetSemanticInfo(ExpressionSyntax expression);
''' SemanticInfo SemanticModel.BindExpression(SyntaxNode location, ExpressionSyntax expression);
''' SemanticInfo SemanticModel.BindType(SyntaxNode location, ExpressionSyntax type);
''' SemanticInfo SemanticModel.BindNamespaceOrType(SyntaxNode location, ExpressionSyntax type);
''' </pre>
''' Also, the following are affected if container=Nothing (and, for the latter, when container=Nothing or arity=0):
''' <pre>
''' Public Function LookupNames(position As Integer, Optional container As NamespaceOrTypeSymbol = Nothing, Optional options As LookupOptions = LookupOptions.Default, Optional results As List(Of String) = Nothing) As IList(Of String)
''' Public Function LookupSymbols(position As Integer,
''' Optional container As NamespaceOrTypeSymbol = Nothing,
''' Optional name As String = Nothing,
''' Optional arity As Integer? = Nothing,
''' Optional options As LookupOptions = LookupOptions.Default,
''' Optional results As List(Of Symbol) = Nothing) As IList(Of Symbol)
''' </pre>
''' </summary>
Friend NotInheritable Class AliasSymbol
Inherits Symbol
Implements IAliasSymbol
Private ReadOnly _aliasTarget As NamespaceOrTypeSymbol
Private ReadOnly _aliasName As String
Private ReadOnly _aliasLocations As ImmutableArray(Of Location)
Private ReadOnly _aliasContainer As Symbol
Friend Sub New(compilation As VisualBasicCompilation,
aliasContainer As Symbol,
aliasName As String,
aliasTarget As NamespaceOrTypeSymbol,
aliasLocation As Location)
Dim merged = TryCast(aliasContainer, MergedNamespaceSymbol)
Dim sourceNs As NamespaceSymbol = Nothing
If merged IsNot Nothing Then
sourceNs = merged.GetConstituentForCompilation(compilation)
End If
Me._aliasContainer = If(sourceNs, aliasContainer)
Me._aliasTarget = aliasTarget
Me._aliasName = aliasName
Me._aliasLocations = ImmutableArray.Create(aliasLocation)
End Sub
''' <summary>
''' The alias name.
''' </summary>
Public Overrides ReadOnly Property Name As String
Get
Return _aliasName
End Get
End Property
''' <summary>
''' Gets the kind of this symbol.
''' </summary>
''' <returns><see cref="SymbolKind.Alias"/></returns>
Public Overrides ReadOnly Property Kind As SymbolKind
Get
Return SymbolKind.Alias
End Get
End Property
''' <summary>
''' Gets the <see cref="NamespaceOrTypeSymbol"/> for the
''' namespace or type referenced by the alias.
''' </summary>
Public ReadOnly Property Target As NamespaceOrTypeSymbol
Get
Return Me._aliasTarget
End Get
End Property
Private ReadOnly Property IAliasSymbol_Target As INamespaceOrTypeSymbol Implements IAliasSymbol.Target
Get
Return Target
End Get
End Property
''' <summary>
''' Gets the locations where this symbol was originally defined.
''' </summary>
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return _aliasLocations
End Get
End Property
''' <summary>
''' Get the syntax node(s) where this symbol was declared in source.
''' </summary>
''' <returns>
''' The syntax node(s) that declared the symbol.
''' </returns>
''' <remarks>
''' To go the opposite direction (from syntax node to symbol), see <see cref="VBSemanticModel.GetDeclaredSymbol"/>.
''' </remarks>
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return GetDeclaringSyntaxReferenceHelper(Of SimpleImportsClauseSyntax)(Locations)
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members and was
''' also restricted from further overriding; i.e., declared with the "NotOverridable"
''' modifier. Never returns true for types.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsNotOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared as requiring an override; i.e., declared
''' with the "MustOverride" modifier. Never returns true for types.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsMustOverride As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol was declared to override a base class members; i.e., declared
''' with the "Overrides" modifier. Still returns true if the members was declared
''' to override something, but (erroneously) no member to override exists.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsOverrides As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this member is overridable, has an implementation,
''' and does not override a base class member; i.e., declared with the "Overridable"
''' modifier. Does not return true for members declared as MustOverride or Overrides.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsOverridable As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Returns true if this symbol is "shared"; i.e., declared with the "Shared"
''' modifier or implicitly always shared.
''' </summary>
''' <returns>False</returns>
Public Overrides ReadOnly Property IsShared As Boolean
Get
Return False
End Get
End Property
''' <summary>
''' Get this accessibility that was declared on this symbol. For symbols that do
''' not have accessibility declared on them, returns NotApplicable.
''' </summary>
''' <returns><see cref="Accessibility.NotApplicable"/></returns>
Public Overrides ReadOnly Property DeclaredAccessibility As Accessibility
Get
Return Accessibility.NotApplicable
End Get
End Property
Friend Overrides ReadOnly Property ObsoleteAttributeData As ObsoleteAttributeData
Get
Return Nothing
End Get
End Property
''' <summary>
''' Get the symbol that logically contains this symbol.
''' </summary>
''' <returns>
''' Using aliases in VB are always at the top
''' level within a compilation unit, within the [Global] namespace declaration. We
''' return that as the "containing" symbol, even though the alias isn't a member of the
''' namespace as such.
''' </returns>
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _aliasContainer
End Get
End Property
''' <summary>
''' Determines whether the specified object is equal to the current object.
''' </summary>
''' <param name="obj">
''' The object to compare with the current object.
''' </param>
Public Overrides Function Equals(obj As Object) As Boolean
If obj Is Me Then
Return True
ElseIf obj Is Nothing Then
Return False
End If
Dim other As AliasSymbol = TryCast(obj, AliasSymbol)
Return other IsNot Nothing AndAlso
Equals(Me.Locations.FirstOrDefault(), other.Locations.FirstOrDefault()) AndAlso
Me.ContainingAssembly Is other.ContainingAssembly
End Function
''' <summary>
''' Returns a hash code for the current object.
''' </summary>
Public Overrides Function GetHashCode() As Integer
Return If(Me.Locations.Length > 0, Me.Locations(0).GetHashCode(), Me.Name.GetHashCode())
End Function
Friend Overrides Function Accept(Of TArg, TResult)(visitor As VisualBasicSymbolVisitor(Of TArg, TResult), a As TArg) As TResult
Return visitor.VisitAlias(Me, a)
End Function
Public Overrides Sub Accept(visitor As SymbolVisitor)
visitor.VisitAlias(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As SymbolVisitor(Of TResult)) As TResult
Return visitor.VisitAlias(Me)
End Function
Public Overrides Sub Accept(visitor As VisualBasicSymbolVisitor)
visitor.VisitAlias(Me)
End Sub
Public Overrides Function Accept(Of TResult)(visitor As VisualBasicSymbolVisitor(Of TResult)) As TResult
Return visitor.VisitAlias(Me)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/VisualBasicTest/Completion/CompletionProviders/TypeImportCompletionProviderTests.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.Completion
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
<UseExportProvider>
Public Class TypeImportCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Private Property ShowImportCompletionItemsOptionValue As Boolean = True
Private Property IsExpandedCompletion As Boolean = True
Private Property UsePartialSemantic As Boolean = False
Protected Overrides Function WithChangedOptions(options As OptionSet) As OptionSet
Return options _
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, ShowImportCompletionItemsOptionValue) _
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) _
.WithChangedOption(CompletionServiceOptions.UsePartialSemanticForImportCompletion, UsePartialSemantic)
End Function
Protected Overrides Function GetComposition() As TestComposition
Return MyBase.GetComposition().AddParts(GetType(TestExperimentationService))
End Function
Friend Overrides Function GetCompletionProviderType() As Type
Return GetType(TypeImportCompletionProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function AttributeTypeInAttributeNameContext() As Task
Dim file1 = <Text>
Namespace Foo
Public Class MyAttribute
Inherits System.Attribute
End Class
Public Class MyVBClass
End Class
Public Class MyAttributeWithoutSuffix
Inherits System.Attribute
End Class
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
<$$
Sub Main()
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttribute", isComplexTextEdit:=True)
Await VerifyItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription:="Foo") ' We intentionally ignore attribute types without proper suffix for perf reason
Await VerifyItemIsAbsentAsync(markup, "MyAttribute", inlineDescription:="Foo")
Await VerifyItemIsAbsentAsync(markup, "MyVBClass", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function AttributeTypeInNonAttributeNameContext() As Task
Dim file1 = <Text>
Namespace Foo
Public Class MyAttribute
Inherits System.Attribute
End Class
Public Class MyVBClass
End Class
Public Class MyAttributeWithoutSuffix
Inherits System.Attribute
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
Sub Main()
Dim x As $$
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "MyAttribute", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttribute", isComplexTextEdit:=True)
Await VerifyItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttributeWithoutSuffix", isComplexTextEdit:=True)
Await VerifyItemExistsAsync(markup, "MyVBClass", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyVBClass", isComplexTextEdit:=True)
Await VerifyItemIsAbsentAsync(markup, "My", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function AttributeTypeInAttributeNameContext2() As Task
' attribute suffix isn't capitalized
Dim file1 = <Text>
Namespace Foo
Public Class Myattribute
Inherits System.Attribute
End Class
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
<$$
Sub Main()
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.Myattribute")
Await VerifyItemIsAbsentAsync(markup, "Myattribute", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function CSharpAttributeTypeWithoutSuffixInAttributeNameContext() As Task
' attribute suffix isn't capitalized
Dim file1 = <Text>
namespace Foo
{
public class Myattribute : System.Attribute { }
}</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
<$$
Sub Main()
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.VisualBasic, LanguageNames.CSharp)
Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.Myattribute", isComplexTextEdit:=True)
Await VerifyItemIsAbsentAsync(markup, "Myattribute", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35124, "https://github.com/dotnet/roslyn/issues/35124")>
Public Async Function GenericTypeShouldDisplayProperVBSyntax() As Task
Dim file1 = <Text>
Namespace Foo
Public Class MyGenericClass(Of T)
End Class
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
Sub Main()
Dim x As $$
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "MyGenericClass", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", displayTextSuffix:="(Of ...)", expectedDescriptionOrNull:="Class Foo.MyGenericClass(Of T)", isComplexTextEdit:=True)
End Function
<InlineData(SourceCodeKind.Regular)>
<InlineData(SourceCodeKind.Script)>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")>
Public Async Function CommitTypeInImportAliasContextShouldUseFullyQualifiedName(kind As SourceCodeKind) As Task
Dim file1 = <Text>
Namespace Foo
Public Class Bar
End Class
End Namespace</Text>.Value
Dim file2 = "Imports BarAlias = $$"
Dim expectedCodeAfterCommit = "Imports BarAlias = Foo.Bar$$"
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind:=kind)
End Function
<InlineData(SourceCodeKind.Regular)>
<InlineData(SourceCodeKind.Script)>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")>
Public Async Function CommitGenericTypeParameterInImportAliasContextShouldUseFullyQualifiedName(kind As SourceCodeKind) As Task
Dim file1 = <Text>
Namespace Foo
Public Class Bar
End Class
End Namespace</Text>.Value
Dim file2 = "Imports BarAlias = System.Collections.Generic.List(Of $$)"
Dim expectedCodeAfterCommit = "Imports BarAlias = System.Collections.Generic.List(Of Foo.Bar$$)"
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind:=kind)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoCompletionItemWhenAliasExists() As Task
Dim file1 = "
Imports FFF = Foo1.Foo2.Foo3.Foo4
Imports FFF1 = Foo1.Foo2.Foo3.Foo4.Foo5
Namespace Bar
Public Class Bar1
Private Sub EE()
F$$
End Sub
End Class
End Namespace"
Dim file2 = "
Namespace Foo1
Namespace Foo2
Namespace Foo3
Public Class Foo4
Public Class Foo5
End Class
End Class
End Namespace
End Namespace
End Namespace
"
Dim markup = CreateMarkupForSingleProject(file1, file2, LanguageNames.VisualBasic)
Await VerifyItemIsAbsentAsync(markup, "Foo4", inlineDescription:="Foo1.Foo2.Foo3")
Await VerifyItemIsAbsentAsync(markup, "Foo5", inlineDescription:="Foo1.Foo2.Foo3")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAliasHasNoEffectOnGenerics() As Task
Dim file1 = "
Imports FFF = Foo1.Foo2.Foo3.Foo4(Of Int)
Namespace Bar
Public Class Bar1
Private Sub EE()
F$$
End Sub
End Class
End Namespace"
Dim file2 = "
Namespace Foo1
Namespace Foo2
Namespace Foo3
Public Class Foo4(Of T)
End Class
End Namespace
End Namespace
End Namespace"
Dim markup = CreateMarkupForSingleProject(file1, file2, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "Foo4", glyph:=Glyph.ClassPublic, inlineDescription:="Foo1.Foo2.Foo3", displayTextSuffix:="(Of ...)", isComplexTextEdit:=True)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Completion
Imports Microsoft.CodeAnalysis.Options
Imports Microsoft.CodeAnalysis.VisualBasic.Completion.Providers
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Completion.CompletionProviders
<UseExportProvider>
Public Class TypeImportCompletionProviderTests
Inherits AbstractVisualBasicCompletionProviderTests
Private Property ShowImportCompletionItemsOptionValue As Boolean = True
Private Property IsExpandedCompletion As Boolean = True
Private Property UsePartialSemantic As Boolean = False
Protected Overrides Function WithChangedOptions(options As OptionSet) As OptionSet
Return options _
.WithChangedOption(CompletionOptions.ShowItemsFromUnimportedNamespaces, LanguageNames.VisualBasic, ShowImportCompletionItemsOptionValue) _
.WithChangedOption(CompletionServiceOptions.IsExpandedCompletion, IsExpandedCompletion) _
.WithChangedOption(CompletionServiceOptions.UsePartialSemanticForImportCompletion, UsePartialSemantic)
End Function
Protected Overrides Function GetComposition() As TestComposition
Return MyBase.GetComposition().AddParts(GetType(TestExperimentationService))
End Function
Friend Overrides Function GetCompletionProviderType() As Type
Return GetType(TypeImportCompletionProvider)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function AttributeTypeInAttributeNameContext() As Task
Dim file1 = <Text>
Namespace Foo
Public Class MyAttribute
Inherits System.Attribute
End Class
Public Class MyVBClass
End Class
Public Class MyAttributeWithoutSuffix
Inherits System.Attribute
End Class
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
<$$
Sub Main()
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttribute", isComplexTextEdit:=True)
Await VerifyItemIsAbsentAsync(markup, "MyAttributeWithoutSuffix", inlineDescription:="Foo") ' We intentionally ignore attribute types without proper suffix for perf reason
Await VerifyItemIsAbsentAsync(markup, "MyAttribute", inlineDescription:="Foo")
Await VerifyItemIsAbsentAsync(markup, "MyVBClass", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function AttributeTypeInNonAttributeNameContext() As Task
Dim file1 = <Text>
Namespace Foo
Public Class MyAttribute
Inherits System.Attribute
End Class
Public Class MyVBClass
End Class
Public Class MyAttributeWithoutSuffix
Inherits System.Attribute
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
Sub Main()
Dim x As $$
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "MyAttribute", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttribute", isComplexTextEdit:=True)
Await VerifyItemExistsAsync(markup, "MyAttributeWithoutSuffix", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyAttributeWithoutSuffix", isComplexTextEdit:=True)
Await VerifyItemExistsAsync(markup, "MyVBClass", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.MyVBClass", isComplexTextEdit:=True)
Await VerifyItemIsAbsentAsync(markup, "My", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function AttributeTypeInAttributeNameContext2() As Task
' attribute suffix isn't capitalized
Dim file1 = <Text>
Namespace Foo
Public Class Myattribute
Inherits System.Attribute
End Class
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
<$$
Sub Main()
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.Myattribute")
Await VerifyItemIsAbsentAsync(markup, "Myattribute", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35540, "https://github.com/dotnet/roslyn/issues/35540")>
Public Async Function CSharpAttributeTypeWithoutSuffixInAttributeNameContext() As Task
' attribute suffix isn't capitalized
Dim file1 = <Text>
namespace Foo
{
public class Myattribute : System.Attribute { }
}</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
<$$
Sub Main()
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForProjectWithProjectReference(file2, file1, LanguageNames.VisualBasic, LanguageNames.CSharp)
Await VerifyItemExistsAsync(markup, "My", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", expectedDescriptionOrNull:="Class Foo.Myattribute", isComplexTextEdit:=True)
Await VerifyItemIsAbsentAsync(markup, "Myattribute", inlineDescription:="Foo")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(35124, "https://github.com/dotnet/roslyn/issues/35124")>
Public Async Function GenericTypeShouldDisplayProperVBSyntax() As Task
Dim file1 = <Text>
Namespace Foo
Public Class MyGenericClass(Of T)
End Class
End Namespace</Text>.Value
Dim file2 = <Text><![CDATA[
Public Class Bar
Sub Main()
Dim x As $$
End Sub
End Class]]></Text>.Value
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "MyGenericClass", glyph:=Glyph.ClassPublic, inlineDescription:="Foo", displayTextSuffix:="(Of ...)", expectedDescriptionOrNull:="Class Foo.MyGenericClass(Of T)", isComplexTextEdit:=True)
End Function
<InlineData(SourceCodeKind.Regular)>
<InlineData(SourceCodeKind.Script)>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")>
Public Async Function CommitTypeInImportAliasContextShouldUseFullyQualifiedName(kind As SourceCodeKind) As Task
Dim file1 = <Text>
Namespace Foo
Public Class Bar
End Class
End Namespace</Text>.Value
Dim file2 = "Imports BarAlias = $$"
Dim expectedCodeAfterCommit = "Imports BarAlias = Foo.Bar$$"
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind:=kind)
End Function
<InlineData(SourceCodeKind.Regular)>
<InlineData(SourceCodeKind.Script)>
<WpfTheory, Trait(Traits.Feature, Traits.Features.Completion)>
<WorkItem(37038, "https://github.com/dotnet/roslyn/issues/37038")>
Public Async Function CommitGenericTypeParameterInImportAliasContextShouldUseFullyQualifiedName(kind As SourceCodeKind) As Task
Dim file1 = <Text>
Namespace Foo
Public Class Bar
End Class
End Namespace</Text>.Value
Dim file2 = "Imports BarAlias = System.Collections.Generic.List(Of $$)"
Dim expectedCodeAfterCommit = "Imports BarAlias = System.Collections.Generic.List(Of Foo.Bar$$)"
Dim markup = CreateMarkupForSingleProject(file2, file1, LanguageNames.VisualBasic)
Await VerifyCustomCommitProviderAsync(markup, "Bar", expectedCodeAfterCommit, sourceCodeKind:=kind)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestNoCompletionItemWhenAliasExists() As Task
Dim file1 = "
Imports FFF = Foo1.Foo2.Foo3.Foo4
Imports FFF1 = Foo1.Foo2.Foo3.Foo4.Foo5
Namespace Bar
Public Class Bar1
Private Sub EE()
F$$
End Sub
End Class
End Namespace"
Dim file2 = "
Namespace Foo1
Namespace Foo2
Namespace Foo3
Public Class Foo4
Public Class Foo5
End Class
End Class
End Namespace
End Namespace
End Namespace
"
Dim markup = CreateMarkupForSingleProject(file1, file2, LanguageNames.VisualBasic)
Await VerifyItemIsAbsentAsync(markup, "Foo4", inlineDescription:="Foo1.Foo2.Foo3")
Await VerifyItemIsAbsentAsync(markup, "Foo5", inlineDescription:="Foo1.Foo2.Foo3")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.Completion)>
Public Async Function TestAliasHasNoEffectOnGenerics() As Task
Dim file1 = "
Imports FFF = Foo1.Foo2.Foo3.Foo4(Of Int)
Namespace Bar
Public Class Bar1
Private Sub EE()
F$$
End Sub
End Class
End Namespace"
Dim file2 = "
Namespace Foo1
Namespace Foo2
Namespace Foo3
Public Class Foo4(Of T)
End Class
End Namespace
End Namespace
End Namespace"
Dim markup = CreateMarkupForSingleProject(file1, file2, LanguageNames.VisualBasic)
Await VerifyItemExistsAsync(markup, "Foo4", glyph:=Glyph.ClassPublic, inlineDescription:="Foo1.Foo2.Foo3", displayTextSuffix:="(Of ...)", isComplexTextEdit:=True)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/CSharp/Portable/Symbols/TypeSymbolExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static partial class TypeSymbolExtensions
{
public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
foreach (NamedTypeSymbol @interface in subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
if (@interface.IsInterface && TypeSymbol.Equals(@interface, superInterface, TypeCompareKind.ConsiderEverything2))
{
return true;
}
}
return false;
}
public static bool CanBeAssignedNull(this TypeSymbol type)
{
return type.IsReferenceType || type.IsPointerOrFunctionPointer() || type.IsNullableType();
}
public static bool CanContainNull(this TypeSymbol type)
{
// unbound type parameters might contain null, even though they cannot be *assigned* null.
return !type.IsValueType || type.IsNullableTypeOrTypeParameter();
}
public static bool CanBeConst(this TypeSymbol typeSymbol)
{
RoslynDebug.Assert((object)typeSymbol != null);
return typeSymbol.IsReferenceType || typeSymbol.IsEnumType() || typeSymbol.SpecialType.CanBeConst() || typeSymbol.IsNativeIntegerType;
}
/// <summary>
/// Assuming that nullable annotations are enabled:
/// T => true
/// T where T : struct => false
/// T where T : class => false
/// T where T : class? => true
/// T where T : IComparable => true
/// T where T : IComparable? => true
/// T where T : notnull => true
/// </summary>
/// <remarks>
/// In C#9, annotations are allowed regardless of constraints.
/// </remarks>
public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type)
{
if (type.TypeKind != TypeKind.TypeParameter)
{
return false;
}
var typeParameter = (TypeParameterSymbol)type;
// https://github.com/dotnet/roslyn/issues/30056: Test `where T : unmanaged`. See
// UninitializedNonNullableFieldTests.TypeParameterConstraints for instance.
return !typeParameter.IsValueType && !(typeParameter.IsReferenceType && typeParameter.IsNotNullable == true);
}
/// <summary>
/// Assuming that nullable annotations are enabled:
/// T => true
/// T where T : struct => false
/// T where T : class => false
/// T where T : class? => true
/// T where T : IComparable => false
/// T where T : IComparable? => true
/// </summary>
public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type)
{
return type is TypeParameterSymbol { IsValueType: false, IsNotNullable: false };
}
public static bool IsNonNullableValueType(this TypeSymbol typeArgument)
{
if (!typeArgument.IsValueType)
{
return false;
}
return !IsNullableTypeOrTypeParameter(typeArgument);
}
public static bool IsVoidType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_Void;
}
public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type)
{
if (type is null)
{
return false;
}
if (type.TypeKind == TypeKind.TypeParameter)
{
var constraintTypes = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics;
foreach (var constraintType in constraintTypes)
{
if (constraintType.Type.IsNullableTypeOrTypeParameter())
{
return true;
}
}
return false;
}
return type.IsNullableType();
}
/// <summary>
/// Is this System.Nullable`1 type, or its substitution.
///
/// To check whether a type is System.Nullable`1 or is a type parameter constrained to System.Nullable`1
/// use <see cref="TypeSymbolExtensions.IsNullableTypeOrTypeParameter" /> instead.
/// </summary>
public static bool IsNullableType(this TypeSymbol type)
{
return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
}
public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type)
{
return type.GetNullableUnderlyingTypeWithAnnotations().Type;
}
public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
RoslynDebug.Assert(IsNullableType(type));
RoslynDebug.Assert(type is NamedTypeSymbol); //not testing Kind because it may be an ErrorType
return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0];
}
public static TypeSymbol StrippedType(this TypeSymbol type)
{
return type.IsNullableType() ? type.GetNullableUnderlyingType() : type;
}
public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type)
{
return type.GetEnumUnderlyingType() ?? type;
}
public static bool IsNativeIntegerOrNullableNativeIntegerType(this TypeSymbol? type)
{
return type?.StrippedType().IsNativeIntegerType == true;
}
public static bool IsObjectType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_Object;
}
public static bool IsStringType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_String;
}
public static bool IsCharType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_Char;
}
public static bool IsIntegralType(this TypeSymbol type)
{
return type.SpecialType.IsIntegralType();
}
public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type)
{
return (type is NamedTypeSymbol namedType) ? namedType.EnumUnderlyingType : null;
}
public static bool IsEnumType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Enum;
}
public static bool IsValidEnumType(this TypeSymbol type)
{
var underlyingType = type.GetEnumUnderlyingType();
// SpecialType will be None if the underlying type is invalid.
return (underlyingType is object) && (underlyingType.SpecialType != SpecialType.None);
}
/// <summary>
/// Determines if the given type is a valid attribute parameter type.
/// </summary>
/// <param name="type">Type to validated</param>
/// <param name="compilation">compilation</param>
/// <returns></returns>
public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation)
{
return GetAttributeParameterTypedConstantKind(type, compilation) != TypedConstantKind.Error;
}
/// <summary>
/// Gets the typed constant kind for the given attribute parameter type.
/// </summary>
/// <param name="type">Type to validated</param>
/// <param name="compilation">compilation</param>
/// <returns>TypedConstantKind for the attribute parameter type.</returns>
public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation)
{
// Spec (17.1.3)
// The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
// 1) One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
// 2) The type object.
// 3) The type System.Type.
// 4) An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
// 5) Single-dimensional arrays of the above types.
// A constructor argument or public field which does not have one of these types, cannot be used as a positional
// or named parameter in an attribute specification.
TypedConstantKind kind = TypedConstantKind.Error;
if ((object)type == null)
{
return TypedConstantKind.Error;
}
if (type.Kind == SymbolKind.ArrayType)
{
var arrayType = (ArrayTypeSymbol)type;
if (!arrayType.IsSZArray)
{
return TypedConstantKind.Error;
}
kind = TypedConstantKind.Array;
type = arrayType.ElementType;
}
// enum or enum[]
if (type.IsEnumType())
{
// SPEC VIOLATION: Dev11 doesn't enforce either the Enum type or its enclosing types (if any) to have public accessibility.
// We will be consistent with Dev11 behavior.
if (kind == TypedConstantKind.Error)
{
// set only if kind is not already set (i.e. its not an array of enum)
kind = TypedConstantKind.Enum;
}
type = type.GetEnumUnderlyingType()!;
}
var typedConstantKind = TypedConstant.GetTypedConstantKind(type, compilation);
switch (typedConstantKind)
{
case TypedConstantKind.Array:
case TypedConstantKind.Enum:
case TypedConstantKind.Error:
return TypedConstantKind.Error;
default:
if (kind == TypedConstantKind.Array || kind == TypedConstantKind.Enum)
{
// Array/Enum type with valid element/underlying type
return kind;
}
return typedConstantKind;
}
}
public static bool IsValidExtensionParameterType(this TypeSymbol type)
{
switch (type.TypeKind)
{
case TypeKind.Pointer:
case TypeKind.Dynamic:
case TypeKind.FunctionPointer:
return false;
default:
return true;
}
}
public static bool IsInterfaceType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)type).IsInterface;
}
public static bool IsClassType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Class;
}
public static bool IsStructType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Struct;
}
public static bool IsErrorType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.Kind == SymbolKind.ErrorType;
}
public static bool IsMethodTypeParameter(this TypeParameterSymbol p)
{
return p.ContainingSymbol.Kind == SymbolKind.Method;
}
public static bool IsDynamic(this TypeSymbol type)
{
return type.TypeKind == TypeKind.Dynamic;
}
public static bool IsTypeParameter(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.TypeParameter;
}
public static bool IsArray(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Array;
}
public static bool IsSZArray(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Array && ((ArrayTypeSymbol)type).IsSZArray;
}
public static bool IsFunctionPointer(this TypeSymbol type)
{
return type.TypeKind == TypeKind.FunctionPointer;
}
public static bool IsPointerOrFunctionPointer(this TypeSymbol type)
{
switch (type.TypeKind)
{
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
default:
return false;
}
}
// If the type is a delegate type, it returns it. If the type is an
// expression tree type associated with a delegate type, it returns
// the delegate type. Otherwise, null.
public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type)
{
if (type is null) return null;
if (type.IsExpressionTree())
{
type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type;
}
return type.IsDelegateType() ? (NamedTypeSymbol)type : null;
}
public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type)
{
return (TypeSymbol?)GetDelegateType(type) ?? type as FunctionPointerTypeSymbol;
}
/// <summary>
/// return true if the type is constructed from System.Linq.Expressions.Expression`1
/// </summary>
public static bool IsExpressionTree(this TypeSymbol type)
{
return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && isGenericType;
}
public static bool IsNonGenericExpressionType(this TypeSymbol type)
{
return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && !isGenericType;
}
public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType)
{
if (_type.OriginalDefinition is NamedTypeSymbol type &&
type.Name == "Expression" &&
CheckFullName(type.ContainingSymbol, s_expressionsNamespaceName))
{
if (type.Arity == 0)
{
isGenericType = false;
return true;
}
if (type.Arity == 1 &&
type.MangleName)
{
isGenericType = true;
return true;
}
}
isGenericType = false;
return false;
}
/// <summary>
/// return true if the type is constructed from a generic interface that
/// might be implemented by an array.
/// </summary>
public static bool IsPossibleArrayGenericInterface(this TypeSymbol type)
{
if (!(type is NamedTypeSymbol t))
{
return false;
}
t = t.OriginalDefinition;
SpecialType st = t.SpecialType;
if (st == SpecialType.System_Collections_Generic_IList_T ||
st == SpecialType.System_Collections_Generic_ICollection_T ||
st == SpecialType.System_Collections_Generic_IEnumerable_T ||
st == SpecialType.System_Collections_Generic_IReadOnlyList_T ||
st == SpecialType.System_Collections_Generic_IReadOnlyCollection_T)
{
return true;
}
return false;
}
private static readonly string[] s_expressionsNamespaceName = { "Expressions", "Linq", MetadataHelpers.SystemString, "" };
private static bool CheckFullName(Symbol symbol, string[] names)
{
for (int i = 0; i < names.Length; i++)
{
if ((object)symbol == null || symbol.Name != names[i]) return false;
symbol = symbol.ContainingSymbol;
}
return true;
}
public static bool IsDelegateType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Delegate;
}
public static ImmutableArray<ParameterSymbol> DelegateParameters(this TypeSymbol type)
{
var invokeMethod = type.DelegateInvokeMethod();
if ((object)invokeMethod == null)
{
return default(ImmutableArray<ParameterSymbol>);
}
return invokeMethod.Parameters;
}
public static ImmutableArray<ParameterSymbol> DelegateOrFunctionPointerParameters(this TypeSymbol type)
{
Debug.Assert(type is FunctionPointerTypeSymbol || type.IsDelegateType());
if (type is FunctionPointerTypeSymbol { Signature: { Parameters: var functionPointerParameters } })
{
return functionPointerParameters;
}
else
{
return type.DelegateParameters();
}
}
public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray<TypeWithAnnotations> elementTypes)
{
if (type.IsTupleType)
{
elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations;
return true;
}
// source not a tuple
elementTypes = default(ImmutableArray<TypeWithAnnotations>);
return false;
}
public static MethodSymbol DelegateInvokeMethod(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
RoslynDebug.Assert(type.IsDelegateType() || type.IsExpressionTree());
return type.GetDelegateType()!.DelegateInvokeMethod;
}
/// <summary>
/// Return the default value constant for the given type,
/// or null if the default value is not a constant.
/// </summary>
public static ConstantValue? GetDefaultValue(this TypeSymbol type)
{
// SPEC: A default-value-expression is a constant expression (§7.19) if the type
// SPEC: is a reference type or a type parameter that is known to be a reference type (§10.1.5).
// SPEC: In addition, a default-value-expression is a constant expression if the type is
// SPEC: one of the following value types:
// SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type.
RoslynDebug.Assert((object)type != null);
if (type.IsErrorType())
{
return null;
}
if (type.IsReferenceType)
{
return ConstantValue.Null;
}
if (type.IsValueType)
{
type = type.EnumUnderlyingTypeOrSelf();
switch (type.SpecialType)
{
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_IntPtr when type.IsNativeIntegerType:
case SpecialType.System_UIntPtr when type.IsNativeIntegerType:
case SpecialType.System_Char:
case SpecialType.System_Boolean:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Decimal:
return ConstantValue.Default(type.SpecialType);
}
}
return null;
}
public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type)
{
return type is object ? type.SpecialType : SpecialType.None;
}
public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
CompoundUseSiteInfo<AssemblySymbol> localUseSiteInfo = useSiteInfo;
var result = type.VisitType((type1, symbol, unused) => IsTypeLessVisibleThan(type1, symbol, ref localUseSiteInfo), sym,
canDigThroughNullable: true); // System.Nullable is public
useSiteInfo = localUseSiteInfo;
return result is null;
}
private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
switch (type.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Enum:
case TypeKind.Delegate:
case TypeKind.Submission:
return !IsAsRestrictive((NamedTypeSymbol)type, sym, ref useSiteInfo);
default:
return false;
}
}
/// <summary>
/// Visit the given type and, in the case of compound types, visit all "sub type"
/// (such as A in A[], or { A<T>, T, U } in A<T>.B<U>) invoking 'predicate'
/// with the type and 'arg' at each sub type. If the predicate returns true for any type,
/// traversal stops and that type is returned from this method. Otherwise if traversal
/// completes without the predicate returning true for any type, this method returns null.
/// </summary>
public static TypeSymbol? VisitType<T>(
this TypeSymbol type,
Func<TypeSymbol, T, bool, bool> predicate,
T arg,
bool canDigThroughNullable = false)
{
return VisitType(
typeWithAnnotationsOpt: default,
type: type,
typeWithAnnotationsPredicate: null,
typePredicate: predicate,
arg,
canDigThroughNullable);
}
/// <summary>
/// Visit the given type and, in the case of compound types, visit all "sub type".
/// One of the predicates will be invoked at each type. If the type is a
/// TypeWithAnnotations, <paramref name="typeWithAnnotationsPredicate"/>
/// will be invoked; otherwise <paramref name="typePredicate"/> will be invoked.
/// If the corresponding predicate returns true for any type,
/// traversal stops and that type is returned from this method. Otherwise if traversal
/// completes without the predicate returning true for any type, this method returns null.
/// </summary>
/// <param name="useDefaultType">If true, use <see cref="TypeWithAnnotations.DefaultType"/>
/// instead of <see cref="TypeWithAnnotations.Type"/> to avoid early resolution of nullable types</param>
public static TypeSymbol? VisitType<T>(
this TypeWithAnnotations typeWithAnnotationsOpt,
TypeSymbol? type,
Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate,
Func<TypeSymbol, T, bool, bool>? typePredicate,
T arg,
bool canDigThroughNullable = false,
bool useDefaultType = false)
{
RoslynDebug.Assert(typeWithAnnotationsOpt.HasType == (type is null));
RoslynDebug.Assert(canDigThroughNullable == false || useDefaultType == false, "digging through nullable will cause early resolution of nullable types");
// In order to handle extremely "deep" types like "int[][][][][][][][][]...[]"
// or int*****************...* we implement manual tail recursion rather than
// doing the natural recursion.
while (true)
{
TypeSymbol current = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type);
bool isNestedNamedType = false;
// Visit containing types from outer-most to inner-most.
switch (current.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Enum:
case TypeKind.Delegate:
{
var containingType = current.ContainingType;
if ((object)containingType != null)
{
isNestedNamedType = true;
var result = VisitType(default, containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType);
if (result is object)
{
return result;
}
}
}
break;
case TypeKind.Submission:
RoslynDebug.Assert((object)current.ContainingType == null);
break;
}
if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null)
{
if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, isNestedNamedType))
{
return current;
}
}
else if (typePredicate != null)
{
if (typePredicate(current, arg, isNestedNamedType))
{
return current;
}
}
TypeWithAnnotations next;
switch (current.TypeKind)
{
case TypeKind.Dynamic:
case TypeKind.TypeParameter:
case TypeKind.Submission:
case TypeKind.Enum:
return null;
case TypeKind.Error:
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Delegate:
var typeArguments = ((NamedTypeSymbol)current).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics;
if (typeArguments.IsEmpty)
{
return null;
}
int i;
for (i = 0; i < typeArguments.Length - 1; i++)
{
// Let's try to avoid early resolution of nullable types
(TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(typeArguments[i], canDigThroughNullable);
var result = VisitType(
typeWithAnnotationsOpt: nextTypeWithAnnotations,
type: nextType,
typeWithAnnotationsPredicate,
typePredicate,
arg,
canDigThroughNullable,
useDefaultType);
if (result is object)
{
return result;
}
}
next = typeArguments[i];
break;
case TypeKind.Array:
next = ((ArrayTypeSymbol)current).ElementTypeWithAnnotations;
break;
case TypeKind.Pointer:
next = ((PointerTypeSymbol)current).PointedAtTypeWithAnnotations;
break;
case TypeKind.FunctionPointer:
{
var result = visitFunctionPointerType((FunctionPointerTypeSymbol)current, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, out next);
if (result is object)
{
return result;
}
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(current.TypeKind);
}
// Let's try to avoid early resolution of nullable types
typeWithAnnotationsOpt = canDigThroughNullable ? default : next;
type = canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null;
}
static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations type, bool canDigThroughNullable)
=> canDigThroughNullable ? (default(TypeWithAnnotations), type.NullableUnderlyingTypeOrSelf) : (type, null);
static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool useDefaultType, bool canDigThroughNullable, out TypeWithAnnotations next)
{
MethodSymbol currentPointer = type.Signature;
if (currentPointer.ParameterCount == 0)
{
next = currentPointer.ReturnTypeWithAnnotations;
return null;
}
var result = VisitType(
typeWithAnnotationsOpt: canDigThroughNullable ? default : currentPointer.ReturnTypeWithAnnotations,
type: canDigThroughNullable ? currentPointer.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null,
typeWithAnnotationsPredicate,
typePredicate,
arg,
canDigThroughNullable,
useDefaultType);
if (result is object)
{
next = default;
return result;
}
int i;
for (i = 0; i < currentPointer.ParameterCount - 1; i++)
{
(TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(currentPointer.Parameters[i].TypeWithAnnotations, canDigThroughNullable);
result = VisitType(
typeWithAnnotationsOpt: nextTypeWithAnnotations,
type: nextType,
typeWithAnnotationsPredicate,
typePredicate,
arg,
canDigThroughNullable,
useDefaultType);
if (result is object)
{
next = default;
return result;
}
}
next = currentPointer.Parameters[i].TypeWithAnnotations;
return null;
}
}
private static bool IsAsRestrictive(NamedTypeSymbol s1, Symbol sym2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Accessibility acc1 = s1.DeclaredAccessibility;
if (acc1 == Accessibility.Public)
{
return true;
}
for (Symbol s2 = sym2; s2.Kind != SymbolKind.Namespace; s2 = s2.ContainingSymbol)
{
Accessibility acc2 = s2.DeclaredAccessibility;
switch (acc1)
{
case Accessibility.Internal:
{
// If s2 is private or internal, and within the same assembly as s1,
// then this is at least as restrictive as s1's internal.
if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
return true;
}
break;
}
case Accessibility.ProtectedAndInternal:
// Since s1 is private protected, s2 must pass the test for being both more restrictive than internal and more restrictive than protected.
// We first do the "internal" test (copied from above), then if it passes we continue with the "protected" test.
if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
// passed the internal test; now do the test for the protected case
goto case Accessibility.Protected;
}
break;
case Accessibility.Protected:
{
var parent1 = s1.ContainingType;
if ((object)parent1 == null)
{
// not helpful
}
else if (acc2 == Accessibility.Private)
{
// if s2 is private and within s1's parent or within a subclass of s1's parent,
// then this is at least as restrictive as s1's protected.
for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType)
{
if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo))
{
return true;
}
}
}
else if (acc2 == Accessibility.Protected || acc2 == Accessibility.ProtectedAndInternal)
{
// if s2 is protected, and it's parent is a subclass (or the same as) s1's parent
// then this is at least as restrictive as s1's protected
var parent2 = s2.ContainingType;
if ((object)parent2 != null && parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo))
{
return true;
}
}
break;
}
case Accessibility.ProtectedOrInternal:
{
var parent1 = s1.ContainingType;
if ((object)parent1 == null)
{
break;
}
switch (acc2)
{
case Accessibility.Private:
// if s2 is private and within a subclass of s1's parent,
// or within the same assembly as s1
// then this is at least as restrictive as s1's internal protected.
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
return true;
}
for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType)
{
if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo))
{
return true;
}
}
break;
case Accessibility.Internal:
// If s2 is in the same assembly as s1, then this is more restrictive
// than s1's internal protected.
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
return true;
}
break;
case Accessibility.Protected:
// if s2 is protected, and it's parent is a subclass (or the same as) s1's parent
// then this is at least as restrictive as s1's internal protected
if (parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo))
{
return true;
}
break;
case Accessibility.ProtectedAndInternal:
// if s2 is private protected, and it's parent is a subclass (or the same as) s1's parent
// or its in the same assembly as s1, then this is at least as restrictive as s1's protected
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) ||
parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo))
{
return true;
}
break;
case Accessibility.ProtectedOrInternal:
// if s2 is internal protected, and it's parent is a subclass (or the same as) s1's parent
// and its in the same assembly as s1, then this is at least as restrictive as s1's protected
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) &&
parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo))
{
return true;
}
break;
}
break;
}
case Accessibility.Private:
if (acc2 == Accessibility.Private)
{
// if s2 is private, and it is within s1's parent, then this is at
// least as restrictive as s1's private.
NamedTypeSymbol parent1 = s1.ContainingType;
if ((object)parent1 == null)
{
break;
}
var parent1OriginalDefinition = parent1.OriginalDefinition;
for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType)
{
if (ReferenceEquals(parent2.OriginalDefinition, parent1OriginalDefinition) || parent1OriginalDefinition.TypeKind == TypeKind.Submission && parent2.TypeKind == TypeKind.Submission)
{
return true;
}
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(acc1);
}
}
return false;
}
public static bool IsUnboundGenericType(this TypeSymbol type)
{
return type is NamedTypeSymbol { IsUnboundGenericType: true };
}
public static bool IsTopLevelType(this NamedTypeSymbol type)
{
return (object)type.ContainingType == null;
}
/// <summary>
/// (null TypeParameterSymbol "parameter"): Checks if the given type is a type parameter
/// or its referent type is a type parameter (array/pointer) or contains a type parameter (aggregate type)
/// (non-null TypeParameterSymbol "parameter"): above + also checks if the type parameter
/// is the same as "parameter"
/// </summary>
public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null)
{
var result = type.VisitType(s_containsTypeParameterPredicate, parameter);
return result is object;
}
private static readonly Func<TypeSymbol, TypeParameterSymbol?, bool, bool> s_containsTypeParameterPredicate =
(type, parameter, unused) => type.TypeKind == TypeKind.TypeParameter && (parameter is null || TypeSymbol.Equals(type, parameter, TypeCompareKind.ConsiderEverything2));
public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer)
{
RoslynDebug.Assert((object)parameterContainer != null);
var result = type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer);
return result is object;
}
private static readonly Func<TypeSymbol, Symbol, bool, bool> s_isTypeParameterWithSpecificContainerPredicate =
(type, parameterContainer, unused) => type.TypeKind == TypeKind.TypeParameter && (object)type.ContainingSymbol == (object)parameterContainer;
public static bool ContainsTypeParameters(this TypeSymbol type, HashSet<TypeParameterSymbol> parameters)
{
var result = type.VisitType(s_containsTypeParametersPredicate, parameters);
return result is object;
}
private static readonly Func<TypeSymbol, HashSet<TypeParameterSymbol>, bool, bool> s_containsTypeParametersPredicate =
(type, parameters, unused) => type.TypeKind == TypeKind.TypeParameter && parameters.Contains((TypeParameterSymbol)type);
public static bool ContainsMethodTypeParameter(this TypeSymbol type)
{
var result = type.VisitType(s_containsMethodTypeParameterPredicate, null);
return result is object;
}
private static readonly Func<TypeSymbol, object?, bool, bool> s_containsMethodTypeParameterPredicate =
(type, _, _) => type.TypeKind == TypeKind.TypeParameter && type.ContainingSymbol is MethodSymbol;
/// <summary>
/// Return true if the type contains any dynamic type reference.
/// </summary>
public static bool ContainsDynamic(this TypeSymbol type)
{
var result = type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true);
return result is object;
}
private static readonly Func<TypeSymbol, object?, bool, bool> s_containsDynamicPredicate = (type, unused1, unused2) => type.TypeKind == TypeKind.Dynamic;
internal static bool ContainsNativeInteger(this TypeSymbol type)
{
var result = type.VisitType((type, unused1, unused2) => type.IsNativeIntegerType, (object?)null, canDigThroughNullable: true);
return result is object;
}
internal static bool ContainsNativeInteger(this TypeWithAnnotations type)
{
return type.Type?.ContainsNativeInteger() == true;
}
internal static bool ContainsErrorType(this TypeSymbol type)
{
var result = type.VisitType((type, unused1, unused2) => type.IsErrorType(), (object?)null, canDigThroughNullable: true);
return result is object;
}
/// <summary>
/// Return true if the type contains any tuples.
/// </summary>
internal static bool ContainsTuple(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) is object;
/// <summary>
/// Return true if the type contains any tuples with element names.
/// </summary>
internal static bool ContainsTupleNames(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) is object;
/// <summary>
/// Return true if the type contains any function pointer types.
/// </summary>
internal static bool ContainsFunctionPointer(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object;
/// <summary>
/// Guess the non-error type that the given type was intended to represent.
/// If the type itself is not an error type, then it will be returned.
/// Otherwise, the underlying type (if any) of the error type will be
/// returned.
/// </summary>
/// <remarks>
/// Any non-null type symbol returned is guaranteed not to be an error type.
///
/// It is possible to pass in a constructed type and received back an
/// unconstructed type. This can occur when the type passed in was
/// constructed from an error type - the underlying definition will be
/// available, but there won't be a good way to "re-substitute" back up
/// to the level of the specified type.
/// </remarks>
internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type)
{
var result = ExtendedErrorTypeSymbol.ExtractNonErrorType(type);
RoslynDebug.Assert((object?)result == null || !result.IsErrorType());
return result;
}
/// <summary>
/// Guess the non-error type kind that the given type was intended to represent,
/// if possible. If not, return TypeKind.Error.
/// </summary>
internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type)
{
return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type);
}
/// <summary>
/// Returns true if the type was a valid switch expression type in C# 6. We use this test to determine
/// whether or not we should attempt a user-defined conversion from the type to a C# 6 switch governing
/// type, which we support for compatibility with C# 6 and earlier.
/// </summary>
internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false)
{
// SPEC: The governing type of a switch statement is established by the switch expression.
// SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint,
// SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type
// SPEC: corresponding to one of these types, then that is the governing type of the switch statement.
// SPEC: 2) Otherwise, exactly one user-defined implicit conversion must exist from the
// SPEC: type of the switch expression to one of the following possible governing types:
// SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type
// SPEC: corresponding to one of those types
RoslynDebug.Assert((object)type != null);
if (type.IsNullableType())
{
type = type.GetNullableUnderlyingType();
}
// User-defined implicit conversion with target type as Enum type is not valid.
if (!isTargetTypeOfUserDefinedOp)
{
type = type.EnumUnderlyingTypeOrSelf();
}
switch (type.SpecialType)
{
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Char:
case SpecialType.System_String:
return true;
case SpecialType.System_Boolean:
// User-defined implicit conversion with target type as bool type is not valid.
return !isTargetTypeOfUserDefinedOp;
}
return false;
}
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <summary>
/// Returns true if the type is one of the restricted types, namely: <see cref="T:System.TypedReference"/>,
/// <see cref="T:System.ArgIterator"/>, or <see cref="T:System.RuntimeArgumentHandle"/>.
/// or a ref-like type.
/// </summary>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
internal static bool IsRestrictedType(this TypeSymbol type,
bool ignoreSpanLikeTypes = false)
{
// See Dev10 C# compiler, "type.cpp", bool Type::isSpecialByRefType() const
RoslynDebug.Assert((object)type != null);
switch (type.SpecialType)
{
case SpecialType.System_TypedReference:
case SpecialType.System_ArgIterator:
case SpecialType.System_RuntimeArgumentHandle:
return true;
}
return ignoreSpanLikeTypes ?
false :
type.IsRefLikeType;
}
public static bool IsIntrinsicType(this TypeSymbol type)
{
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_IntPtr when type.IsNativeIntegerType:
case SpecialType.System_UIntPtr when type.IsNativeIntegerType:
case SpecialType.System_Single:
case SpecialType.System_Double:
// NOTE: VB treats System.DateTime as an intrinsic, while C# does not.
//case SpecialType.System_DateTime:
case SpecialType.System_Decimal:
return true;
default:
return false;
}
}
public static bool IsPartial(this TypeSymbol type)
{
return type is SourceNamedTypeSymbol { IsPartial: true };
}
public static bool IsPointerType(this TypeSymbol type)
{
return type is PointerTypeSymbol;
}
internal static int FixedBufferElementSizeInBytes(this TypeSymbol type)
{
return type.SpecialType.FixedBufferElementSizeInBytes();
}
// check that its type is allowed for Volatile
internal static bool IsValidVolatileFieldType(this TypeSymbol type)
{
switch (type.TypeKind)
{
case TypeKind.Struct:
return type.SpecialType.IsValidVolatileFieldType();
case TypeKind.Array:
case TypeKind.Class:
case TypeKind.Delegate:
case TypeKind.Dynamic:
case TypeKind.Error:
case TypeKind.Interface:
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
case TypeKind.Enum:
return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType();
case TypeKind.TypeParameter:
return type.IsReferenceType;
case TypeKind.Submission:
throw ExceptionUtilities.UnexpectedValue(type.TypeKind);
}
return false;
}
/// <summary>
/// Add this instance to the set of checked types. Returns true
/// if this was added, false if the type was already in the set.
/// </summary>
public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet<TypeSymbol> checkedTypes)
{
if (checkedTypes == null)
{
checkedTypes = new HashSet<TypeSymbol>();
}
return checkedTypes.Add(type);
}
internal static bool IsUnsafe(this TypeSymbol type)
{
while (true)
{
switch (type.TypeKind)
{
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
case TypeKind.Array:
type = ((ArrayTypeSymbol)type).ElementType;
break;
default:
// NOTE: we could consider a generic type with unsafe type arguments to be unsafe,
// but that's already an error, so there's no reason to report it. Also, this
// matches Type::isUnsafe in Dev10.
return false;
}
}
}
internal static bool IsVoidPointer(this TypeSymbol type)
{
return type is PointerTypeSymbol p && p.PointedAtType.IsVoidType();
}
/// <summary>
/// These special types are structs that contain fields of the same type
/// (e.g. <see cref="System.Int32"/> contains an instance field of type <see cref="System.Int32"/>).
/// </summary>
internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t)
{
return t.SpecialType.IsPrimitiveRecursiveStruct();
}
/// <summary>
/// Compute a hash code for the constructed type. The return value will be
/// non-zero so callers can used zero to represent an uninitialized value.
/// </summary>
internal static int ComputeHashCode(this NamedTypeSymbol type)
{
RoslynDebug.Assert(!type.Equals(type.OriginalDefinition, TypeCompareKind.AllIgnoreOptions) || wasConstructedForAnnotations(type));
if (wasConstructedForAnnotations(type))
{
// A type that uses its own type parameters as type arguments was constructed only for the purpose of adding annotations.
// In that case we'll use the hash from the definition.
return type.OriginalDefinition.GetHashCode();
}
int code = type.OriginalDefinition.GetHashCode();
code = Hash.Combine(type.ContainingType, code);
// Unconstructed type may contain alpha-renamed type parameters while
// may still be considered equal, we do not want to give different hashcode to such types.
//
// Example:
// Having original type A<U>.B<V> we create two _unconstructed_ types
// A<int>.B<V'>
// A<int>.B<V">
// Note that V' and V" are type parameters substituted via alpha-renaming of original V
// These are different objects, but represent the same "type parameter at index 1"
//
// In short - we are not interested in the type parameters of unconstructed types.
if ((object)type.ConstructedFrom != (object)type)
{
foreach (var arg in type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics)
{
code = Hash.Combine(arg.Type, code);
}
}
// 0 may be used by the caller to indicate the hashcode is not
// initialized. If we computed 0 for the hashcode, tweak it.
if (code == 0)
{
code++;
}
return code;
static bool wasConstructedForAnnotations(NamedTypeSymbol type)
{
do
{
var typeArguments = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics;
var typeParameters = type.OriginalDefinition.TypeParameters;
for (int i = 0; i < typeArguments.Length; i++)
{
if (!typeParameters[i].Equals(
typeArguments[i].Type.OriginalDefinition,
TypeCompareKind.ConsiderEverything))
{
return false;
}
}
type = type.ContainingType;
}
while (type is object && !type.IsDefinition);
return true;
}
}
/// <summary>
/// If we are in a COM PIA with embedInteropTypes enabled we should turn properties and methods
/// that have the type and return type of object, respectively, into type dynamic. If the requisite conditions
/// are fulfilled, this method returns a dynamic type. If not, it returns the original type.
/// </summary>
/// <param name="type">A property type or method return type to be checked for dynamification.</param>
/// <param name="containingType">Containing type.</param>
/// <returns></returns>
public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType)
{
return type.TryAsDynamicIfNoPia(containingType, out TypeSymbol? result) ? result : type;
}
public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result)
{
if (type.SpecialType == SpecialType.System_Object)
{
AssemblySymbol assembly = containingType.ContainingAssembly;
if ((object)assembly != null &&
assembly.IsLinked &&
containingType.IsComImport)
{
result = DynamicTypeSymbol.Instance;
return true;
}
}
result = null;
return false;
}
/// <summary>
/// Type variables are never considered reference types by the verifier.
/// </summary>
internal static bool IsVerifierReference(this TypeSymbol type)
{
return type.IsReferenceType && type.TypeKind != TypeKind.TypeParameter;
}
/// <summary>
/// Type variables are never considered value types by the verifier.
/// </summary>
internal static bool IsVerifierValue(this TypeSymbol type)
{
return type.IsValueType && type.TypeKind != TypeKind.TypeParameter;
}
/// <summary>
/// Return all of the type parameters in this type and enclosing types,
/// from outer-most to inner-most type.
/// </summary>
internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this NamedTypeSymbol type)
{
// Avoid allocating a builder in the common case.
if ((object)type.ContainingType == null)
{
return type.TypeParameters;
}
var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance();
type.GetAllTypeParameters(builder);
return builder.ToImmutableAndFree();
}
/// <summary>
/// Return all of the type parameters in this type and enclosing types,
/// from outer-most to inner-most type.
/// </summary>
internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder<TypeParameterSymbol> result)
{
var containingType = type.ContainingType;
if ((object)containingType != null)
{
containingType.GetAllTypeParameters(result);
}
result.AddRange(type.TypeParameters);
}
/// <summary>
/// Return the nearest type parameter with the given name in
/// this type or any enclosing type.
/// </summary>
internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name)
{
var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance();
type.GetAllTypeParameters(allTypeParameters);
TypeParameterSymbol? result = null;
foreach (TypeParameterSymbol tpEnclosing in allTypeParameters)
{
if (name == tpEnclosing.Name)
{
result = tpEnclosing;
break;
}
}
allTypeParameters.Free();
return result;
}
/// <summary>
/// Return the nearest type parameter with the given name in
/// this symbol or any enclosing symbol.
/// </summary>
internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name)
{
while (methodOrType != null)
{
switch (methodOrType.Kind)
{
case SymbolKind.Method:
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
case SymbolKind.Field:
case SymbolKind.Property:
case SymbolKind.Event:
break;
default:
return null;
}
foreach (var typeParameter in methodOrType.GetMemberTypeParameters())
{
if (typeParameter.Name == name)
{
return typeParameter;
}
}
methodOrType = methodOrType.ContainingSymbol;
}
return null;
}
/// <summary>
/// Return true if the fully qualified name of the type's containing symbol
/// matches the given name. This method avoids string concatenations
/// in the common case where the type is a top-level type.
/// </summary>
internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName)
{
const StringComparison comparison = StringComparison.Ordinal;
var container = type.ContainingSymbol;
if (container.Kind != SymbolKind.Namespace)
{
// Nested type. For simplicity, compare qualified name to SymbolDisplay result.
return string.Equals(container.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, comparison);
}
var @namespace = (NamespaceSymbol)container;
if (@namespace.IsGlobalNamespace)
{
return qualifiedName.Length == 0;
}
return HasNamespaceName(@namespace, qualifiedName, comparison, length: qualifiedName.Length);
}
private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length)
{
if (length == 0)
{
return false;
}
var container = @namespace.ContainingNamespace;
int separator = namespaceName.LastIndexOf('.', length - 1, length);
int offset = 0;
if (separator >= 0)
{
if (container.IsGlobalNamespace)
{
return false;
}
if (!HasNamespaceName(container, namespaceName, comparison, length: separator))
{
return false;
}
int n = separator + 1;
offset = n;
length -= n;
}
else if (!container.IsGlobalNamespace)
{
return false;
}
var name = @namespace.Name;
return (name.Length == length) && (string.Compare(name, 0, namespaceName, offset, length, comparison) == 0);
}
internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation)
{
var namedType = type as NamedTypeSymbol;
if (namedType is null || namedType.Arity != 0)
{
return false;
}
if ((object)namedType == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task))
{
return true;
}
if (namedType.IsVoidType())
{
return false;
}
return namedType.IsCustomTaskType(builderArgument: out _);
}
internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation)
{
if (!(type is NamedTypeSymbol { Arity: 1 } namedType))
{
return false;
}
if ((object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T))
{
return true;
}
return namedType.IsCustomTaskType(builderArgument: out _);
}
internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation)
{
if (!(type is NamedTypeSymbol { Arity: 1 } namedType))
{
return false;
}
return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T);
}
internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation)
{
if (!(type is NamedTypeSymbol { Arity: 1 } namedType))
{
return false;
}
return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T);
}
/// <summary>
/// Returns true if the type is generic or non-generic custom task-like type due to the
/// [AsyncMethodBuilder(typeof(B))] attribute. It returns the "B".
/// </summary>
/// <remarks>
/// For the Task types themselves, this method might return true or false depending on mscorlib.
/// The definition of "custom task-like type" is one that has an [AsyncMethodBuilder(typeof(B))] attribute,
/// no more, no less. Validation of builder type B is left for elsewhere. This method returns B
/// without validation of any kind.
/// </remarks>
internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument)
{
RoslynDebug.Assert((object)type != null);
var arity = type.Arity;
if (arity < 2)
{
return type.HasAsyncMethodBuilderAttribute(out builderArgument);
}
builderArgument = null;
return false;
}
/// <summary>
/// Replace Task-like types with Task types.
/// </summary>
internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation)
{
NormalizeTaskTypesInType(compilation, ref type);
return type;
}
/// <summary>
/// Replace Task-like types with Task types. Returns true if there were changes.
/// </summary>
private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type)
{
switch (type.Kind)
{
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
{
var namedType = (NamedTypeSymbol)type;
var changed = NormalizeTaskTypesInNamedType(compilation, ref namedType);
type = namedType;
return changed;
}
case SymbolKind.ArrayType:
{
var arrayType = (ArrayTypeSymbol)type;
var changed = NormalizeTaskTypesInArray(compilation, ref arrayType);
type = arrayType;
return changed;
}
case SymbolKind.PointerType:
{
var pointerType = (PointerTypeSymbol)type;
var changed = NormalizeTaskTypesInPointer(compilation, ref pointerType);
type = pointerType;
return changed;
}
case SymbolKind.FunctionPointerType:
{
var functionPointerType = (FunctionPointerTypeSymbol)type;
var changed = NormalizeTaskTypesInFunctionPointer(compilation, ref functionPointerType);
type = functionPointerType;
return changed;
}
}
return false;
}
private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations)
{
var type = typeWithAnnotations.Type;
if (NormalizeTaskTypesInType(compilation, ref type))
{
typeWithAnnotations = TypeWithAnnotations.Create(type, customModifiers: typeWithAnnotations.CustomModifiers);
return true;
}
return false;
}
private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type)
{
bool hasChanged = false;
if (!type.IsDefinition)
{
RoslynDebug.Assert(type.IsGenericType);
var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance();
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
type.GetAllTypeArguments(typeArgumentsBuilder, ref discardedUseSiteInfo);
for (int i = 0; i < typeArgumentsBuilder.Count; i++)
{
var typeWithModifier = typeArgumentsBuilder[i];
var typeArgNormalized = typeWithModifier.Type;
if (NormalizeTaskTypesInType(compilation, ref typeArgNormalized))
{
hasChanged = true;
// Preserve custom modifiers but without normalizing those types.
typeArgumentsBuilder[i] = TypeWithAnnotations.Create(typeArgNormalized, customModifiers: typeWithModifier.CustomModifiers);
}
}
if (hasChanged)
{
var originalType = type;
var originalDefinition = originalType.OriginalDefinition;
var typeParameters = originalDefinition.GetAllTypeParameters();
var typeMap = new TypeMap(typeParameters, typeArgumentsBuilder.ToImmutable(), allowAlpha: true);
type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(originalType);
}
typeArgumentsBuilder.Free();
}
if (type.OriginalDefinition.IsCustomTaskType(builderArgument: out _))
{
int arity = type.Arity;
RoslynDebug.Assert(arity < 2);
var taskType = compilation.GetWellKnownType(
arity == 0 ?
WellKnownType.System_Threading_Tasks_Task :
WellKnownType.System_Threading_Tasks_Task_T);
if (taskType.TypeKind == TypeKind.Error)
{
// Skip if Task types are not available.
return false;
}
type = arity == 0 ?
taskType :
taskType.Construct(
ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]),
unbound: false);
hasChanged = true;
}
return hasChanged;
}
private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType)
{
var elementType = arrayType.ElementTypeWithAnnotations;
if (!NormalizeTaskTypesInType(compilation, ref elementType))
{
return false;
}
arrayType = arrayType.WithElementType(elementType);
return true;
}
private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType)
{
var pointedAtType = pointerType.PointedAtTypeWithAnnotations;
if (!NormalizeTaskTypesInType(compilation, ref pointedAtType))
{
return false;
}
// Preserve custom modifiers but without normalizing those types.
pointerType = new PointerTypeSymbol(pointedAtType);
return true;
}
private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType)
{
var returnType = funcPtrType.Signature.ReturnTypeWithAnnotations;
var madeChanges = NormalizeTaskTypesInType(compilation, ref returnType);
var paramTypes = ImmutableArray<TypeWithAnnotations>.Empty;
if (funcPtrType.Signature.ParameterCount > 0)
{
var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(funcPtrType.Signature.ParameterCount);
bool madeParamChanges = false;
foreach (var param in funcPtrType.Signature.Parameters)
{
var paramType = param.TypeWithAnnotations;
madeParamChanges |= NormalizeTaskTypesInType(compilation, ref paramType);
paramsBuilder.Add(paramType);
}
if (madeParamChanges)
{
madeChanges = true;
paramTypes = paramsBuilder.ToImmutableAndFree();
}
else
{
paramTypes = funcPtrType.Signature.ParameterTypesWithAnnotations;
paramsBuilder.Free();
}
}
if (madeChanges)
{
funcPtrType = funcPtrType.SubstituteTypeSymbol(returnType, paramTypes, refCustomModifiers: default, paramRefCustomModifiers: default);
return true;
}
else
{
return false;
}
}
internal static Cci.TypeReferenceWithAttributes GetTypeRefWithAttributes(
this TypeWithAnnotations type,
Emit.PEModuleBuilder moduleBuilder,
Symbol declaringSymbol,
Cci.ITypeReference typeRef)
{
var builder = ArrayBuilder<Cci.ICustomAttribute>.GetInstance();
var compilation = declaringSymbol.DeclaringCompilation;
if (compilation != null)
{
if (type.Type.ContainsTupleNames())
{
addIfNotNull(builder, compilation.SynthesizeTupleNamesAttribute(type.Type));
}
if (type.Type.ContainsNativeInteger())
{
addIfNotNull(builder, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type));
}
if (compilation.ShouldEmitNullableAttributes(declaringSymbol))
{
addIfNotNull(builder, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type));
}
static void addIfNotNull(ArrayBuilder<Cci.ICustomAttribute> builder, SynthesizedAttributeData? attr)
{
if (attr != null)
{
builder.Add(attr);
}
}
}
return new Cci.TypeReferenceWithAttributes(typeRef, builder.ToImmutableAndFree());
}
internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol)
=> typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute");
internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol)
=> typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType");
internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol)
=> typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit");
internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute");
private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name)
{
if (typeSymbol.Name != name || typeSymbol.ContainingType is object)
{
return false;
}
return IsContainedInNamespace(typeSymbol, "System", "Runtime", "InteropServices");
}
private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name)
{
if (typeSymbol.Name != name)
{
return false;
}
return IsCompilerServicesTopLevelType(typeSymbol);
}
internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol)
=> typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Runtime", "CompilerServices");
private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string innerNS)
{
var innerNamespace = typeSymbol.ContainingNamespace;
if (innerNamespace?.Name != innerNS)
{
return false;
}
var midNamespace = innerNamespace.ContainingNamespace;
if (midNamespace?.Name != midNS)
{
return false;
}
var outerNamespace = midNamespace.ContainingNamespace;
if (outerNamespace?.Name != outerNS)
{
return false;
}
var globalNamespace = outerNamespace.ContainingNamespace;
return globalNamespace != null && globalNamespace.IsGlobalNamespace;
}
internal static int TypeToIndex(this TypeSymbol type)
{
switch (type.GetSpecialTypeSafe())
{
case SpecialType.System_Object: return 0;
case SpecialType.System_String: return 1;
case SpecialType.System_Boolean: return 2;
case SpecialType.System_Char: return 3;
case SpecialType.System_SByte: return 4;
case SpecialType.System_Int16: return 5;
case SpecialType.System_Int32: return 6;
case SpecialType.System_Int64: return 7;
case SpecialType.System_Byte: return 8;
case SpecialType.System_UInt16: return 9;
case SpecialType.System_UInt32: return 10;
case SpecialType.System_UInt64: return 11;
case SpecialType.System_IntPtr when type.IsNativeIntegerType: return 12;
case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return 13;
case SpecialType.System_Single: return 14;
case SpecialType.System_Double: return 15;
case SpecialType.System_Decimal: return 16;
case SpecialType.None:
if ((object)type != null && type.IsNullableType())
{
TypeSymbol underlyingType = type.GetNullableUnderlyingType();
switch (underlyingType.GetSpecialTypeSafe())
{
case SpecialType.System_Boolean: return 17;
case SpecialType.System_Char: return 18;
case SpecialType.System_SByte: return 19;
case SpecialType.System_Int16: return 20;
case SpecialType.System_Int32: return 21;
case SpecialType.System_Int64: return 22;
case SpecialType.System_Byte: return 23;
case SpecialType.System_UInt16: return 24;
case SpecialType.System_UInt32: return 25;
case SpecialType.System_UInt64: return 26;
case SpecialType.System_IntPtr when underlyingType.IsNativeIntegerType: return 27;
case SpecialType.System_UIntPtr when underlyingType.IsNativeIntegerType: return 28;
case SpecialType.System_Single: return 29;
case SpecialType.System_Double: return 30;
case SpecialType.System_Decimal: return 31;
}
}
// fall through
goto default;
default: return -1;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal static partial class TypeSymbolExtensions
{
public static bool ImplementsInterface(this TypeSymbol subType, TypeSymbol superInterface, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
foreach (NamedTypeSymbol @interface in subType.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo))
{
if (@interface.IsInterface && TypeSymbol.Equals(@interface, superInterface, TypeCompareKind.ConsiderEverything2))
{
return true;
}
}
return false;
}
public static bool CanBeAssignedNull(this TypeSymbol type)
{
return type.IsReferenceType || type.IsPointerOrFunctionPointer() || type.IsNullableType();
}
public static bool CanContainNull(this TypeSymbol type)
{
// unbound type parameters might contain null, even though they cannot be *assigned* null.
return !type.IsValueType || type.IsNullableTypeOrTypeParameter();
}
public static bool CanBeConst(this TypeSymbol typeSymbol)
{
RoslynDebug.Assert((object)typeSymbol != null);
return typeSymbol.IsReferenceType || typeSymbol.IsEnumType() || typeSymbol.SpecialType.CanBeConst() || typeSymbol.IsNativeIntegerType;
}
/// <summary>
/// Assuming that nullable annotations are enabled:
/// T => true
/// T where T : struct => false
/// T where T : class => false
/// T where T : class? => true
/// T where T : IComparable => true
/// T where T : IComparable? => true
/// T where T : notnull => true
/// </summary>
/// <remarks>
/// In C#9, annotations are allowed regardless of constraints.
/// </remarks>
public static bool IsTypeParameterDisallowingAnnotationInCSharp8(this TypeSymbol type)
{
if (type.TypeKind != TypeKind.TypeParameter)
{
return false;
}
var typeParameter = (TypeParameterSymbol)type;
// https://github.com/dotnet/roslyn/issues/30056: Test `where T : unmanaged`. See
// UninitializedNonNullableFieldTests.TypeParameterConstraints for instance.
return !typeParameter.IsValueType && !(typeParameter.IsReferenceType && typeParameter.IsNotNullable == true);
}
/// <summary>
/// Assuming that nullable annotations are enabled:
/// T => true
/// T where T : struct => false
/// T where T : class => false
/// T where T : class? => true
/// T where T : IComparable => false
/// T where T : IComparable? => true
/// </summary>
public static bool IsPossiblyNullableReferenceTypeTypeParameter(this TypeSymbol type)
{
return type is TypeParameterSymbol { IsValueType: false, IsNotNullable: false };
}
public static bool IsNonNullableValueType(this TypeSymbol typeArgument)
{
if (!typeArgument.IsValueType)
{
return false;
}
return !IsNullableTypeOrTypeParameter(typeArgument);
}
public static bool IsVoidType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_Void;
}
public static bool IsNullableTypeOrTypeParameter(this TypeSymbol? type)
{
if (type is null)
{
return false;
}
if (type.TypeKind == TypeKind.TypeParameter)
{
var constraintTypes = ((TypeParameterSymbol)type).ConstraintTypesNoUseSiteDiagnostics;
foreach (var constraintType in constraintTypes)
{
if (constraintType.Type.IsNullableTypeOrTypeParameter())
{
return true;
}
}
return false;
}
return type.IsNullableType();
}
/// <summary>
/// Is this System.Nullable`1 type, or its substitution.
///
/// To check whether a type is System.Nullable`1 or is a type parameter constrained to System.Nullable`1
/// use <see cref="TypeSymbolExtensions.IsNullableTypeOrTypeParameter" /> instead.
/// </summary>
public static bool IsNullableType(this TypeSymbol type)
{
return type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
}
public static TypeSymbol GetNullableUnderlyingType(this TypeSymbol type)
{
return type.GetNullableUnderlyingTypeWithAnnotations().Type;
}
public static TypeWithAnnotations GetNullableUnderlyingTypeWithAnnotations(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
RoslynDebug.Assert(IsNullableType(type));
RoslynDebug.Assert(type is NamedTypeSymbol); //not testing Kind because it may be an ErrorType
return ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0];
}
public static TypeSymbol StrippedType(this TypeSymbol type)
{
return type.IsNullableType() ? type.GetNullableUnderlyingType() : type;
}
public static TypeSymbol EnumUnderlyingTypeOrSelf(this TypeSymbol type)
{
return type.GetEnumUnderlyingType() ?? type;
}
public static bool IsNativeIntegerOrNullableNativeIntegerType(this TypeSymbol? type)
{
return type?.StrippedType().IsNativeIntegerType == true;
}
public static bool IsObjectType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_Object;
}
public static bool IsStringType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_String;
}
public static bool IsCharType(this TypeSymbol type)
{
return type.SpecialType == SpecialType.System_Char;
}
public static bool IsIntegralType(this TypeSymbol type)
{
return type.SpecialType.IsIntegralType();
}
public static NamedTypeSymbol? GetEnumUnderlyingType(this TypeSymbol? type)
{
return (type is NamedTypeSymbol namedType) ? namedType.EnumUnderlyingType : null;
}
public static bool IsEnumType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Enum;
}
public static bool IsValidEnumType(this TypeSymbol type)
{
var underlyingType = type.GetEnumUnderlyingType();
// SpecialType will be None if the underlying type is invalid.
return (underlyingType is object) && (underlyingType.SpecialType != SpecialType.None);
}
/// <summary>
/// Determines if the given type is a valid attribute parameter type.
/// </summary>
/// <param name="type">Type to validated</param>
/// <param name="compilation">compilation</param>
/// <returns></returns>
public static bool IsValidAttributeParameterType(this TypeSymbol type, CSharpCompilation compilation)
{
return GetAttributeParameterTypedConstantKind(type, compilation) != TypedConstantKind.Error;
}
/// <summary>
/// Gets the typed constant kind for the given attribute parameter type.
/// </summary>
/// <param name="type">Type to validated</param>
/// <param name="compilation">compilation</param>
/// <returns>TypedConstantKind for the attribute parameter type.</returns>
public static TypedConstantKind GetAttributeParameterTypedConstantKind(this TypeSymbol type, CSharpCompilation compilation)
{
// Spec (17.1.3)
// The types of positional and named parameters for an attribute class are limited to the attribute parameter types, which are:
// 1) One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort.
// 2) The type object.
// 3) The type System.Type.
// 4) An enum type, provided it has public accessibility and the types in which it is nested (if any) also have public accessibility.
// 5) Single-dimensional arrays of the above types.
// A constructor argument or public field which does not have one of these types, cannot be used as a positional
// or named parameter in an attribute specification.
TypedConstantKind kind = TypedConstantKind.Error;
if ((object)type == null)
{
return TypedConstantKind.Error;
}
if (type.Kind == SymbolKind.ArrayType)
{
var arrayType = (ArrayTypeSymbol)type;
if (!arrayType.IsSZArray)
{
return TypedConstantKind.Error;
}
kind = TypedConstantKind.Array;
type = arrayType.ElementType;
}
// enum or enum[]
if (type.IsEnumType())
{
// SPEC VIOLATION: Dev11 doesn't enforce either the Enum type or its enclosing types (if any) to have public accessibility.
// We will be consistent with Dev11 behavior.
if (kind == TypedConstantKind.Error)
{
// set only if kind is not already set (i.e. its not an array of enum)
kind = TypedConstantKind.Enum;
}
type = type.GetEnumUnderlyingType()!;
}
var typedConstantKind = TypedConstant.GetTypedConstantKind(type, compilation);
switch (typedConstantKind)
{
case TypedConstantKind.Array:
case TypedConstantKind.Enum:
case TypedConstantKind.Error:
return TypedConstantKind.Error;
default:
if (kind == TypedConstantKind.Array || kind == TypedConstantKind.Enum)
{
// Array/Enum type with valid element/underlying type
return kind;
}
return typedConstantKind;
}
}
public static bool IsValidExtensionParameterType(this TypeSymbol type)
{
switch (type.TypeKind)
{
case TypeKind.Pointer:
case TypeKind.Dynamic:
case TypeKind.FunctionPointer:
return false;
default:
return true;
}
}
public static bool IsInterfaceType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.Kind == SymbolKind.NamedType && ((NamedTypeSymbol)type).IsInterface;
}
public static bool IsClassType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Class;
}
public static bool IsStructType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Struct;
}
public static bool IsErrorType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.Kind == SymbolKind.ErrorType;
}
public static bool IsMethodTypeParameter(this TypeParameterSymbol p)
{
return p.ContainingSymbol.Kind == SymbolKind.Method;
}
public static bool IsDynamic(this TypeSymbol type)
{
return type.TypeKind == TypeKind.Dynamic;
}
public static bool IsTypeParameter(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.TypeParameter;
}
public static bool IsArray(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Array;
}
public static bool IsSZArray(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Array && ((ArrayTypeSymbol)type).IsSZArray;
}
public static bool IsFunctionPointer(this TypeSymbol type)
{
return type.TypeKind == TypeKind.FunctionPointer;
}
public static bool IsPointerOrFunctionPointer(this TypeSymbol type)
{
switch (type.TypeKind)
{
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
default:
return false;
}
}
// If the type is a delegate type, it returns it. If the type is an
// expression tree type associated with a delegate type, it returns
// the delegate type. Otherwise, null.
public static NamedTypeSymbol? GetDelegateType(this TypeSymbol? type)
{
if (type is null) return null;
if (type.IsExpressionTree())
{
type = ((NamedTypeSymbol)type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].Type;
}
return type.IsDelegateType() ? (NamedTypeSymbol)type : null;
}
public static TypeSymbol? GetDelegateOrFunctionPointerType(this TypeSymbol? type)
{
return (TypeSymbol?)GetDelegateType(type) ?? type as FunctionPointerTypeSymbol;
}
/// <summary>
/// return true if the type is constructed from System.Linq.Expressions.Expression`1
/// </summary>
public static bool IsExpressionTree(this TypeSymbol type)
{
return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && isGenericType;
}
public static bool IsNonGenericExpressionType(this TypeSymbol type)
{
return type.IsGenericOrNonGenericExpressionType(out bool isGenericType) && !isGenericType;
}
public static bool IsGenericOrNonGenericExpressionType(this TypeSymbol _type, out bool isGenericType)
{
if (_type.OriginalDefinition is NamedTypeSymbol type &&
type.Name == "Expression" &&
CheckFullName(type.ContainingSymbol, s_expressionsNamespaceName))
{
if (type.Arity == 0)
{
isGenericType = false;
return true;
}
if (type.Arity == 1 &&
type.MangleName)
{
isGenericType = true;
return true;
}
}
isGenericType = false;
return false;
}
/// <summary>
/// return true if the type is constructed from a generic interface that
/// might be implemented by an array.
/// </summary>
public static bool IsPossibleArrayGenericInterface(this TypeSymbol type)
{
if (!(type is NamedTypeSymbol t))
{
return false;
}
t = t.OriginalDefinition;
SpecialType st = t.SpecialType;
if (st == SpecialType.System_Collections_Generic_IList_T ||
st == SpecialType.System_Collections_Generic_ICollection_T ||
st == SpecialType.System_Collections_Generic_IEnumerable_T ||
st == SpecialType.System_Collections_Generic_IReadOnlyList_T ||
st == SpecialType.System_Collections_Generic_IReadOnlyCollection_T)
{
return true;
}
return false;
}
private static readonly string[] s_expressionsNamespaceName = { "Expressions", "Linq", MetadataHelpers.SystemString, "" };
private static bool CheckFullName(Symbol symbol, string[] names)
{
for (int i = 0; i < names.Length; i++)
{
if ((object)symbol == null || symbol.Name != names[i]) return false;
symbol = symbol.ContainingSymbol;
}
return true;
}
public static bool IsDelegateType(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
return type.TypeKind == TypeKind.Delegate;
}
public static ImmutableArray<ParameterSymbol> DelegateParameters(this TypeSymbol type)
{
var invokeMethod = type.DelegateInvokeMethod();
if ((object)invokeMethod == null)
{
return default(ImmutableArray<ParameterSymbol>);
}
return invokeMethod.Parameters;
}
public static ImmutableArray<ParameterSymbol> DelegateOrFunctionPointerParameters(this TypeSymbol type)
{
Debug.Assert(type is FunctionPointerTypeSymbol || type.IsDelegateType());
if (type is FunctionPointerTypeSymbol { Signature: { Parameters: var functionPointerParameters } })
{
return functionPointerParameters;
}
else
{
return type.DelegateParameters();
}
}
public static bool TryGetElementTypesWithAnnotationsIfTupleType(this TypeSymbol type, out ImmutableArray<TypeWithAnnotations> elementTypes)
{
if (type.IsTupleType)
{
elementTypes = ((NamedTypeSymbol)type).TupleElementTypesWithAnnotations;
return true;
}
// source not a tuple
elementTypes = default(ImmutableArray<TypeWithAnnotations>);
return false;
}
public static MethodSymbol DelegateInvokeMethod(this TypeSymbol type)
{
RoslynDebug.Assert((object)type != null);
RoslynDebug.Assert(type.IsDelegateType() || type.IsExpressionTree());
return type.GetDelegateType()!.DelegateInvokeMethod;
}
/// <summary>
/// Return the default value constant for the given type,
/// or null if the default value is not a constant.
/// </summary>
public static ConstantValue? GetDefaultValue(this TypeSymbol type)
{
// SPEC: A default-value-expression is a constant expression (§7.19) if the type
// SPEC: is a reference type or a type parameter that is known to be a reference type (§10.1.5).
// SPEC: In addition, a default-value-expression is a constant expression if the type is
// SPEC: one of the following value types:
// SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, or any enumeration type.
RoslynDebug.Assert((object)type != null);
if (type.IsErrorType())
{
return null;
}
if (type.IsReferenceType)
{
return ConstantValue.Null;
}
if (type.IsValueType)
{
type = type.EnumUnderlyingTypeOrSelf();
switch (type.SpecialType)
{
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_IntPtr when type.IsNativeIntegerType:
case SpecialType.System_UIntPtr when type.IsNativeIntegerType:
case SpecialType.System_Char:
case SpecialType.System_Boolean:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Decimal:
return ConstantValue.Default(type.SpecialType);
}
}
return null;
}
public static SpecialType GetSpecialTypeSafe(this TypeSymbol? type)
{
return type is object ? type.SpecialType : SpecialType.None;
}
public static bool IsAtLeastAsVisibleAs(this TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
CompoundUseSiteInfo<AssemblySymbol> localUseSiteInfo = useSiteInfo;
var result = type.VisitType((type1, symbol, unused) => IsTypeLessVisibleThan(type1, symbol, ref localUseSiteInfo), sym,
canDigThroughNullable: true); // System.Nullable is public
useSiteInfo = localUseSiteInfo;
return result is null;
}
private static bool IsTypeLessVisibleThan(TypeSymbol type, Symbol sym, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
switch (type.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Enum:
case TypeKind.Delegate:
case TypeKind.Submission:
return !IsAsRestrictive((NamedTypeSymbol)type, sym, ref useSiteInfo);
default:
return false;
}
}
/// <summary>
/// Visit the given type and, in the case of compound types, visit all "sub type"
/// (such as A in A[], or { A<T>, T, U } in A<T>.B<U>) invoking 'predicate'
/// with the type and 'arg' at each sub type. If the predicate returns true for any type,
/// traversal stops and that type is returned from this method. Otherwise if traversal
/// completes without the predicate returning true for any type, this method returns null.
/// </summary>
public static TypeSymbol? VisitType<T>(
this TypeSymbol type,
Func<TypeSymbol, T, bool, bool> predicate,
T arg,
bool canDigThroughNullable = false)
{
return VisitType(
typeWithAnnotationsOpt: default,
type: type,
typeWithAnnotationsPredicate: null,
typePredicate: predicate,
arg,
canDigThroughNullable);
}
/// <summary>
/// Visit the given type and, in the case of compound types, visit all "sub type".
/// One of the predicates will be invoked at each type. If the type is a
/// TypeWithAnnotations, <paramref name="typeWithAnnotationsPredicate"/>
/// will be invoked; otherwise <paramref name="typePredicate"/> will be invoked.
/// If the corresponding predicate returns true for any type,
/// traversal stops and that type is returned from this method. Otherwise if traversal
/// completes without the predicate returning true for any type, this method returns null.
/// </summary>
/// <param name="useDefaultType">If true, use <see cref="TypeWithAnnotations.DefaultType"/>
/// instead of <see cref="TypeWithAnnotations.Type"/> to avoid early resolution of nullable types</param>
public static TypeSymbol? VisitType<T>(
this TypeWithAnnotations typeWithAnnotationsOpt,
TypeSymbol? type,
Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate,
Func<TypeSymbol, T, bool, bool>? typePredicate,
T arg,
bool canDigThroughNullable = false,
bool useDefaultType = false)
{
RoslynDebug.Assert(typeWithAnnotationsOpt.HasType == (type is null));
RoslynDebug.Assert(canDigThroughNullable == false || useDefaultType == false, "digging through nullable will cause early resolution of nullable types");
// In order to handle extremely "deep" types like "int[][][][][][][][][]...[]"
// or int*****************...* we implement manual tail recursion rather than
// doing the natural recursion.
while (true)
{
TypeSymbol current = type ?? (useDefaultType ? typeWithAnnotationsOpt.DefaultType : typeWithAnnotationsOpt.Type);
bool isNestedNamedType = false;
// Visit containing types from outer-most to inner-most.
switch (current.TypeKind)
{
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Enum:
case TypeKind.Delegate:
{
var containingType = current.ContainingType;
if ((object)containingType != null)
{
isNestedNamedType = true;
var result = VisitType(default, containingType, typeWithAnnotationsPredicate, typePredicate, arg, canDigThroughNullable, useDefaultType);
if (result is object)
{
return result;
}
}
}
break;
case TypeKind.Submission:
RoslynDebug.Assert((object)current.ContainingType == null);
break;
}
if (typeWithAnnotationsOpt.HasType && typeWithAnnotationsPredicate != null)
{
if (typeWithAnnotationsPredicate(typeWithAnnotationsOpt, arg, isNestedNamedType))
{
return current;
}
}
else if (typePredicate != null)
{
if (typePredicate(current, arg, isNestedNamedType))
{
return current;
}
}
TypeWithAnnotations next;
switch (current.TypeKind)
{
case TypeKind.Dynamic:
case TypeKind.TypeParameter:
case TypeKind.Submission:
case TypeKind.Enum:
return null;
case TypeKind.Error:
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.Delegate:
var typeArguments = ((NamedTypeSymbol)current).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics;
if (typeArguments.IsEmpty)
{
return null;
}
int i;
for (i = 0; i < typeArguments.Length - 1; i++)
{
// Let's try to avoid early resolution of nullable types
(TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(typeArguments[i], canDigThroughNullable);
var result = VisitType(
typeWithAnnotationsOpt: nextTypeWithAnnotations,
type: nextType,
typeWithAnnotationsPredicate,
typePredicate,
arg,
canDigThroughNullable,
useDefaultType);
if (result is object)
{
return result;
}
}
next = typeArguments[i];
break;
case TypeKind.Array:
next = ((ArrayTypeSymbol)current).ElementTypeWithAnnotations;
break;
case TypeKind.Pointer:
next = ((PointerTypeSymbol)current).PointedAtTypeWithAnnotations;
break;
case TypeKind.FunctionPointer:
{
var result = visitFunctionPointerType((FunctionPointerTypeSymbol)current, typeWithAnnotationsPredicate, typePredicate, arg, useDefaultType, canDigThroughNullable, out next);
if (result is object)
{
return result;
}
break;
}
default:
throw ExceptionUtilities.UnexpectedValue(current.TypeKind);
}
// Let's try to avoid early resolution of nullable types
typeWithAnnotationsOpt = canDigThroughNullable ? default : next;
type = canDigThroughNullable ? next.NullableUnderlyingTypeOrSelf : null;
}
static (TypeWithAnnotations, TypeSymbol?) getNextIterationElements(TypeWithAnnotations type, bool canDigThroughNullable)
=> canDigThroughNullable ? (default(TypeWithAnnotations), type.NullableUnderlyingTypeOrSelf) : (type, null);
static TypeSymbol? visitFunctionPointerType(FunctionPointerTypeSymbol type, Func<TypeWithAnnotations, T, bool, bool>? typeWithAnnotationsPredicate, Func<TypeSymbol, T, bool, bool>? typePredicate, T arg, bool useDefaultType, bool canDigThroughNullable, out TypeWithAnnotations next)
{
MethodSymbol currentPointer = type.Signature;
if (currentPointer.ParameterCount == 0)
{
next = currentPointer.ReturnTypeWithAnnotations;
return null;
}
var result = VisitType(
typeWithAnnotationsOpt: canDigThroughNullable ? default : currentPointer.ReturnTypeWithAnnotations,
type: canDigThroughNullable ? currentPointer.ReturnTypeWithAnnotations.NullableUnderlyingTypeOrSelf : null,
typeWithAnnotationsPredicate,
typePredicate,
arg,
canDigThroughNullable,
useDefaultType);
if (result is object)
{
next = default;
return result;
}
int i;
for (i = 0; i < currentPointer.ParameterCount - 1; i++)
{
(TypeWithAnnotations nextTypeWithAnnotations, TypeSymbol? nextType) = getNextIterationElements(currentPointer.Parameters[i].TypeWithAnnotations, canDigThroughNullable);
result = VisitType(
typeWithAnnotationsOpt: nextTypeWithAnnotations,
type: nextType,
typeWithAnnotationsPredicate,
typePredicate,
arg,
canDigThroughNullable,
useDefaultType);
if (result is object)
{
next = default;
return result;
}
}
next = currentPointer.Parameters[i].TypeWithAnnotations;
return null;
}
}
private static bool IsAsRestrictive(NamedTypeSymbol s1, Symbol sym2, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo)
{
Accessibility acc1 = s1.DeclaredAccessibility;
if (acc1 == Accessibility.Public)
{
return true;
}
for (Symbol s2 = sym2; s2.Kind != SymbolKind.Namespace; s2 = s2.ContainingSymbol)
{
Accessibility acc2 = s2.DeclaredAccessibility;
switch (acc1)
{
case Accessibility.Internal:
{
// If s2 is private or internal, and within the same assembly as s1,
// then this is at least as restrictive as s1's internal.
if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
return true;
}
break;
}
case Accessibility.ProtectedAndInternal:
// Since s1 is private protected, s2 must pass the test for being both more restrictive than internal and more restrictive than protected.
// We first do the "internal" test (copied from above), then if it passes we continue with the "protected" test.
if ((acc2 == Accessibility.Private || acc2 == Accessibility.Internal || acc2 == Accessibility.ProtectedAndInternal) && s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
// passed the internal test; now do the test for the protected case
goto case Accessibility.Protected;
}
break;
case Accessibility.Protected:
{
var parent1 = s1.ContainingType;
if ((object)parent1 == null)
{
// not helpful
}
else if (acc2 == Accessibility.Private)
{
// if s2 is private and within s1's parent or within a subclass of s1's parent,
// then this is at least as restrictive as s1's protected.
for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType)
{
if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo))
{
return true;
}
}
}
else if (acc2 == Accessibility.Protected || acc2 == Accessibility.ProtectedAndInternal)
{
// if s2 is protected, and it's parent is a subclass (or the same as) s1's parent
// then this is at least as restrictive as s1's protected
var parent2 = s2.ContainingType;
if ((object)parent2 != null && parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo))
{
return true;
}
}
break;
}
case Accessibility.ProtectedOrInternal:
{
var parent1 = s1.ContainingType;
if ((object)parent1 == null)
{
break;
}
switch (acc2)
{
case Accessibility.Private:
// if s2 is private and within a subclass of s1's parent,
// or within the same assembly as s1
// then this is at least as restrictive as s1's internal protected.
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
return true;
}
for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType)
{
if (parent1.IsAccessibleViaInheritance(parent2, ref useSiteInfo))
{
return true;
}
}
break;
case Accessibility.Internal:
// If s2 is in the same assembly as s1, then this is more restrictive
// than s1's internal protected.
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly))
{
return true;
}
break;
case Accessibility.Protected:
// if s2 is protected, and it's parent is a subclass (or the same as) s1's parent
// then this is at least as restrictive as s1's internal protected
if (parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo))
{
return true;
}
break;
case Accessibility.ProtectedAndInternal:
// if s2 is private protected, and it's parent is a subclass (or the same as) s1's parent
// or its in the same assembly as s1, then this is at least as restrictive as s1's protected
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) ||
parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo))
{
return true;
}
break;
case Accessibility.ProtectedOrInternal:
// if s2 is internal protected, and it's parent is a subclass (or the same as) s1's parent
// and its in the same assembly as s1, then this is at least as restrictive as s1's protected
if (s2.ContainingAssembly.HasInternalAccessTo(s1.ContainingAssembly) &&
parent1.IsAccessibleViaInheritance(s2.ContainingType, ref useSiteInfo))
{
return true;
}
break;
}
break;
}
case Accessibility.Private:
if (acc2 == Accessibility.Private)
{
// if s2 is private, and it is within s1's parent, then this is at
// least as restrictive as s1's private.
NamedTypeSymbol parent1 = s1.ContainingType;
if ((object)parent1 == null)
{
break;
}
var parent1OriginalDefinition = parent1.OriginalDefinition;
for (var parent2 = s2.ContainingType; (object)parent2 != null; parent2 = parent2.ContainingType)
{
if (ReferenceEquals(parent2.OriginalDefinition, parent1OriginalDefinition) || parent1OriginalDefinition.TypeKind == TypeKind.Submission && parent2.TypeKind == TypeKind.Submission)
{
return true;
}
}
}
break;
default:
throw ExceptionUtilities.UnexpectedValue(acc1);
}
}
return false;
}
public static bool IsUnboundGenericType(this TypeSymbol type)
{
return type is NamedTypeSymbol { IsUnboundGenericType: true };
}
public static bool IsTopLevelType(this NamedTypeSymbol type)
{
return (object)type.ContainingType == null;
}
/// <summary>
/// (null TypeParameterSymbol "parameter"): Checks if the given type is a type parameter
/// or its referent type is a type parameter (array/pointer) or contains a type parameter (aggregate type)
/// (non-null TypeParameterSymbol "parameter"): above + also checks if the type parameter
/// is the same as "parameter"
/// </summary>
public static bool ContainsTypeParameter(this TypeSymbol type, TypeParameterSymbol? parameter = null)
{
var result = type.VisitType(s_containsTypeParameterPredicate, parameter);
return result is object;
}
private static readonly Func<TypeSymbol, TypeParameterSymbol?, bool, bool> s_containsTypeParameterPredicate =
(type, parameter, unused) => type.TypeKind == TypeKind.TypeParameter && (parameter is null || TypeSymbol.Equals(type, parameter, TypeCompareKind.ConsiderEverything2));
public static bool ContainsTypeParameter(this TypeSymbol type, MethodSymbol parameterContainer)
{
RoslynDebug.Assert((object)parameterContainer != null);
var result = type.VisitType(s_isTypeParameterWithSpecificContainerPredicate, parameterContainer);
return result is object;
}
private static readonly Func<TypeSymbol, Symbol, bool, bool> s_isTypeParameterWithSpecificContainerPredicate =
(type, parameterContainer, unused) => type.TypeKind == TypeKind.TypeParameter && (object)type.ContainingSymbol == (object)parameterContainer;
public static bool ContainsTypeParameters(this TypeSymbol type, HashSet<TypeParameterSymbol> parameters)
{
var result = type.VisitType(s_containsTypeParametersPredicate, parameters);
return result is object;
}
private static readonly Func<TypeSymbol, HashSet<TypeParameterSymbol>, bool, bool> s_containsTypeParametersPredicate =
(type, parameters, unused) => type.TypeKind == TypeKind.TypeParameter && parameters.Contains((TypeParameterSymbol)type);
public static bool ContainsMethodTypeParameter(this TypeSymbol type)
{
var result = type.VisitType(s_containsMethodTypeParameterPredicate, null);
return result is object;
}
private static readonly Func<TypeSymbol, object?, bool, bool> s_containsMethodTypeParameterPredicate =
(type, _, _) => type.TypeKind == TypeKind.TypeParameter && type.ContainingSymbol is MethodSymbol;
/// <summary>
/// Return true if the type contains any dynamic type reference.
/// </summary>
public static bool ContainsDynamic(this TypeSymbol type)
{
var result = type.VisitType(s_containsDynamicPredicate, null, canDigThroughNullable: true);
return result is object;
}
private static readonly Func<TypeSymbol, object?, bool, bool> s_containsDynamicPredicate = (type, unused1, unused2) => type.TypeKind == TypeKind.Dynamic;
internal static bool ContainsNativeInteger(this TypeSymbol type)
{
var result = type.VisitType((type, unused1, unused2) => type.IsNativeIntegerType, (object?)null, canDigThroughNullable: true);
return result is object;
}
internal static bool ContainsNativeInteger(this TypeWithAnnotations type)
{
return type.Type?.ContainsNativeInteger() == true;
}
internal static bool ContainsErrorType(this TypeSymbol type)
{
var result = type.VisitType((type, unused1, unused2) => type.IsErrorType(), (object?)null, canDigThroughNullable: true);
return result is object;
}
/// <summary>
/// Return true if the type contains any tuples.
/// </summary>
internal static bool ContainsTuple(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _1, bool _2) => t.IsTupleType, null) is object;
/// <summary>
/// Return true if the type contains any tuples with element names.
/// </summary>
internal static bool ContainsTupleNames(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _1, bool _2) => !t.TupleElementNames.IsDefault, null) is object;
/// <summary>
/// Return true if the type contains any function pointer types.
/// </summary>
internal static bool ContainsFunctionPointer(this TypeSymbol type) =>
type.VisitType((TypeSymbol t, object? _, bool _) => t.IsFunctionPointer(), null) is object;
/// <summary>
/// Guess the non-error type that the given type was intended to represent.
/// If the type itself is not an error type, then it will be returned.
/// Otherwise, the underlying type (if any) of the error type will be
/// returned.
/// </summary>
/// <remarks>
/// Any non-null type symbol returned is guaranteed not to be an error type.
///
/// It is possible to pass in a constructed type and received back an
/// unconstructed type. This can occur when the type passed in was
/// constructed from an error type - the underlying definition will be
/// available, but there won't be a good way to "re-substitute" back up
/// to the level of the specified type.
/// </remarks>
internal static TypeSymbol? GetNonErrorGuess(this TypeSymbol type)
{
var result = ExtendedErrorTypeSymbol.ExtractNonErrorType(type);
RoslynDebug.Assert((object?)result == null || !result.IsErrorType());
return result;
}
/// <summary>
/// Guess the non-error type kind that the given type was intended to represent,
/// if possible. If not, return TypeKind.Error.
/// </summary>
internal static TypeKind GetNonErrorTypeKindGuess(this TypeSymbol type)
{
return ExtendedErrorTypeSymbol.ExtractNonErrorTypeKind(type);
}
/// <summary>
/// Returns true if the type was a valid switch expression type in C# 6. We use this test to determine
/// whether or not we should attempt a user-defined conversion from the type to a C# 6 switch governing
/// type, which we support for compatibility with C# 6 and earlier.
/// </summary>
internal static bool IsValidV6SwitchGoverningType(this TypeSymbol type, bool isTargetTypeOfUserDefinedOp = false)
{
// SPEC: The governing type of a switch statement is established by the switch expression.
// SPEC: 1) If the type of the switch expression is sbyte, byte, short, ushort, int, uint,
// SPEC: long, ulong, bool, char, string, or an enum-type, or if it is the nullable type
// SPEC: corresponding to one of these types, then that is the governing type of the switch statement.
// SPEC: 2) Otherwise, exactly one user-defined implicit conversion must exist from the
// SPEC: type of the switch expression to one of the following possible governing types:
// SPEC: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type
// SPEC: corresponding to one of those types
RoslynDebug.Assert((object)type != null);
if (type.IsNullableType())
{
type = type.GetNullableUnderlyingType();
}
// User-defined implicit conversion with target type as Enum type is not valid.
if (!isTargetTypeOfUserDefinedOp)
{
type = type.EnumUnderlyingTypeOrSelf();
}
switch (type.SpecialType)
{
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Char:
case SpecialType.System_String:
return true;
case SpecialType.System_Boolean:
// User-defined implicit conversion with target type as bool type is not valid.
return !isTargetTypeOfUserDefinedOp;
}
return false;
}
#pragma warning disable CA1200 // Avoid using cref tags with a prefix
/// <summary>
/// Returns true if the type is one of the restricted types, namely: <see cref="T:System.TypedReference"/>,
/// <see cref="T:System.ArgIterator"/>, or <see cref="T:System.RuntimeArgumentHandle"/>.
/// or a ref-like type.
/// </summary>
#pragma warning restore CA1200 // Avoid using cref tags with a prefix
internal static bool IsRestrictedType(this TypeSymbol type,
bool ignoreSpanLikeTypes = false)
{
// See Dev10 C# compiler, "type.cpp", bool Type::isSpecialByRefType() const
RoslynDebug.Assert((object)type != null);
switch (type.SpecialType)
{
case SpecialType.System_TypedReference:
case SpecialType.System_ArgIterator:
case SpecialType.System_RuntimeArgumentHandle:
return true;
}
return ignoreSpanLikeTypes ?
false :
type.IsRefLikeType;
}
public static bool IsIntrinsicType(this TypeSymbol type)
{
switch (type.SpecialType)
{
case SpecialType.System_Boolean:
case SpecialType.System_Char:
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_IntPtr when type.IsNativeIntegerType:
case SpecialType.System_UIntPtr when type.IsNativeIntegerType:
case SpecialType.System_Single:
case SpecialType.System_Double:
// NOTE: VB treats System.DateTime as an intrinsic, while C# does not.
//case SpecialType.System_DateTime:
case SpecialType.System_Decimal:
return true;
default:
return false;
}
}
public static bool IsPartial(this TypeSymbol type)
{
return type is SourceNamedTypeSymbol { IsPartial: true };
}
public static bool IsPointerType(this TypeSymbol type)
{
return type is PointerTypeSymbol;
}
internal static int FixedBufferElementSizeInBytes(this TypeSymbol type)
{
return type.SpecialType.FixedBufferElementSizeInBytes();
}
// check that its type is allowed for Volatile
internal static bool IsValidVolatileFieldType(this TypeSymbol type)
{
switch (type.TypeKind)
{
case TypeKind.Struct:
return type.SpecialType.IsValidVolatileFieldType();
case TypeKind.Array:
case TypeKind.Class:
case TypeKind.Delegate:
case TypeKind.Dynamic:
case TypeKind.Error:
case TypeKind.Interface:
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
case TypeKind.Enum:
return ((NamedTypeSymbol)type).EnumUnderlyingType.SpecialType.IsValidVolatileFieldType();
case TypeKind.TypeParameter:
return type.IsReferenceType;
case TypeKind.Submission:
throw ExceptionUtilities.UnexpectedValue(type.TypeKind);
}
return false;
}
/// <summary>
/// Add this instance to the set of checked types. Returns true
/// if this was added, false if the type was already in the set.
/// </summary>
public static bool MarkCheckedIfNecessary(this TypeSymbol type, ref HashSet<TypeSymbol> checkedTypes)
{
if (checkedTypes == null)
{
checkedTypes = new HashSet<TypeSymbol>();
}
return checkedTypes.Add(type);
}
internal static bool IsUnsafe(this TypeSymbol type)
{
while (true)
{
switch (type.TypeKind)
{
case TypeKind.Pointer:
case TypeKind.FunctionPointer:
return true;
case TypeKind.Array:
type = ((ArrayTypeSymbol)type).ElementType;
break;
default:
// NOTE: we could consider a generic type with unsafe type arguments to be unsafe,
// but that's already an error, so there's no reason to report it. Also, this
// matches Type::isUnsafe in Dev10.
return false;
}
}
}
internal static bool IsVoidPointer(this TypeSymbol type)
{
return type is PointerTypeSymbol p && p.PointedAtType.IsVoidType();
}
/// <summary>
/// These special types are structs that contain fields of the same type
/// (e.g. <see cref="System.Int32"/> contains an instance field of type <see cref="System.Int32"/>).
/// </summary>
internal static bool IsPrimitiveRecursiveStruct(this TypeSymbol t)
{
return t.SpecialType.IsPrimitiveRecursiveStruct();
}
/// <summary>
/// Compute a hash code for the constructed type. The return value will be
/// non-zero so callers can used zero to represent an uninitialized value.
/// </summary>
internal static int ComputeHashCode(this NamedTypeSymbol type)
{
RoslynDebug.Assert(!type.Equals(type.OriginalDefinition, TypeCompareKind.AllIgnoreOptions) || wasConstructedForAnnotations(type));
if (wasConstructedForAnnotations(type))
{
// A type that uses its own type parameters as type arguments was constructed only for the purpose of adding annotations.
// In that case we'll use the hash from the definition.
return type.OriginalDefinition.GetHashCode();
}
int code = type.OriginalDefinition.GetHashCode();
code = Hash.Combine(type.ContainingType, code);
// Unconstructed type may contain alpha-renamed type parameters while
// may still be considered equal, we do not want to give different hashcode to such types.
//
// Example:
// Having original type A<U>.B<V> we create two _unconstructed_ types
// A<int>.B<V'>
// A<int>.B<V">
// Note that V' and V" are type parameters substituted via alpha-renaming of original V
// These are different objects, but represent the same "type parameter at index 1"
//
// In short - we are not interested in the type parameters of unconstructed types.
if ((object)type.ConstructedFrom != (object)type)
{
foreach (var arg in type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics)
{
code = Hash.Combine(arg.Type, code);
}
}
// 0 may be used by the caller to indicate the hashcode is not
// initialized. If we computed 0 for the hashcode, tweak it.
if (code == 0)
{
code++;
}
return code;
static bool wasConstructedForAnnotations(NamedTypeSymbol type)
{
do
{
var typeArguments = type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics;
var typeParameters = type.OriginalDefinition.TypeParameters;
for (int i = 0; i < typeArguments.Length; i++)
{
if (!typeParameters[i].Equals(
typeArguments[i].Type.OriginalDefinition,
TypeCompareKind.ConsiderEverything))
{
return false;
}
}
type = type.ContainingType;
}
while (type is object && !type.IsDefinition);
return true;
}
}
/// <summary>
/// If we are in a COM PIA with embedInteropTypes enabled we should turn properties and methods
/// that have the type and return type of object, respectively, into type dynamic. If the requisite conditions
/// are fulfilled, this method returns a dynamic type. If not, it returns the original type.
/// </summary>
/// <param name="type">A property type or method return type to be checked for dynamification.</param>
/// <param name="containingType">Containing type.</param>
/// <returns></returns>
public static TypeSymbol AsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType)
{
return type.TryAsDynamicIfNoPia(containingType, out TypeSymbol? result) ? result : type;
}
public static bool TryAsDynamicIfNoPia(this TypeSymbol type, NamedTypeSymbol containingType, [NotNullWhen(true)] out TypeSymbol? result)
{
if (type.SpecialType == SpecialType.System_Object)
{
AssemblySymbol assembly = containingType.ContainingAssembly;
if ((object)assembly != null &&
assembly.IsLinked &&
containingType.IsComImport)
{
result = DynamicTypeSymbol.Instance;
return true;
}
}
result = null;
return false;
}
/// <summary>
/// Type variables are never considered reference types by the verifier.
/// </summary>
internal static bool IsVerifierReference(this TypeSymbol type)
{
return type.IsReferenceType && type.TypeKind != TypeKind.TypeParameter;
}
/// <summary>
/// Type variables are never considered value types by the verifier.
/// </summary>
internal static bool IsVerifierValue(this TypeSymbol type)
{
return type.IsValueType && type.TypeKind != TypeKind.TypeParameter;
}
/// <summary>
/// Return all of the type parameters in this type and enclosing types,
/// from outer-most to inner-most type.
/// </summary>
internal static ImmutableArray<TypeParameterSymbol> GetAllTypeParameters(this NamedTypeSymbol type)
{
// Avoid allocating a builder in the common case.
if ((object)type.ContainingType == null)
{
return type.TypeParameters;
}
var builder = ArrayBuilder<TypeParameterSymbol>.GetInstance();
type.GetAllTypeParameters(builder);
return builder.ToImmutableAndFree();
}
/// <summary>
/// Return all of the type parameters in this type and enclosing types,
/// from outer-most to inner-most type.
/// </summary>
internal static void GetAllTypeParameters(this NamedTypeSymbol type, ArrayBuilder<TypeParameterSymbol> result)
{
var containingType = type.ContainingType;
if ((object)containingType != null)
{
containingType.GetAllTypeParameters(result);
}
result.AddRange(type.TypeParameters);
}
/// <summary>
/// Return the nearest type parameter with the given name in
/// this type or any enclosing type.
/// </summary>
internal static TypeParameterSymbol? FindEnclosingTypeParameter(this NamedTypeSymbol type, string name)
{
var allTypeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance();
type.GetAllTypeParameters(allTypeParameters);
TypeParameterSymbol? result = null;
foreach (TypeParameterSymbol tpEnclosing in allTypeParameters)
{
if (name == tpEnclosing.Name)
{
result = tpEnclosing;
break;
}
}
allTypeParameters.Free();
return result;
}
/// <summary>
/// Return the nearest type parameter with the given name in
/// this symbol or any enclosing symbol.
/// </summary>
internal static TypeParameterSymbol? FindEnclosingTypeParameter(this Symbol methodOrType, string name)
{
while (methodOrType != null)
{
switch (methodOrType.Kind)
{
case SymbolKind.Method:
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
case SymbolKind.Field:
case SymbolKind.Property:
case SymbolKind.Event:
break;
default:
return null;
}
foreach (var typeParameter in methodOrType.GetMemberTypeParameters())
{
if (typeParameter.Name == name)
{
return typeParameter;
}
}
methodOrType = methodOrType.ContainingSymbol;
}
return null;
}
/// <summary>
/// Return true if the fully qualified name of the type's containing symbol
/// matches the given name. This method avoids string concatenations
/// in the common case where the type is a top-level type.
/// </summary>
internal static bool HasNameQualifier(this NamedTypeSymbol type, string qualifiedName)
{
const StringComparison comparison = StringComparison.Ordinal;
var container = type.ContainingSymbol;
if (container.Kind != SymbolKind.Namespace)
{
// Nested type. For simplicity, compare qualified name to SymbolDisplay result.
return string.Equals(container.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), qualifiedName, comparison);
}
var @namespace = (NamespaceSymbol)container;
if (@namespace.IsGlobalNamespace)
{
return qualifiedName.Length == 0;
}
return HasNamespaceName(@namespace, qualifiedName, comparison, length: qualifiedName.Length);
}
private static bool HasNamespaceName(NamespaceSymbol @namespace, string namespaceName, StringComparison comparison, int length)
{
if (length == 0)
{
return false;
}
var container = @namespace.ContainingNamespace;
int separator = namespaceName.LastIndexOf('.', length - 1, length);
int offset = 0;
if (separator >= 0)
{
if (container.IsGlobalNamespace)
{
return false;
}
if (!HasNamespaceName(container, namespaceName, comparison, length: separator))
{
return false;
}
int n = separator + 1;
offset = n;
length -= n;
}
else if (!container.IsGlobalNamespace)
{
return false;
}
var name = @namespace.Name;
return (name.Length == length) && (string.Compare(name, 0, namespaceName, offset, length, comparison) == 0);
}
internal static bool IsNonGenericTaskType(this TypeSymbol type, CSharpCompilation compilation)
{
var namedType = type as NamedTypeSymbol;
if (namedType is null || namedType.Arity != 0)
{
return false;
}
if ((object)namedType == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task))
{
return true;
}
if (namedType.IsVoidType())
{
return false;
}
return namedType.IsCustomTaskType(builderArgument: out _);
}
internal static bool IsGenericTaskType(this TypeSymbol type, CSharpCompilation compilation)
{
if (!(type is NamedTypeSymbol { Arity: 1 } namedType))
{
return false;
}
if ((object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T))
{
return true;
}
return namedType.IsCustomTaskType(builderArgument: out _);
}
internal static bool IsIAsyncEnumerableType(this TypeSymbol type, CSharpCompilation compilation)
{
if (!(type is NamedTypeSymbol { Arity: 1 } namedType))
{
return false;
}
return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerable_T);
}
internal static bool IsIAsyncEnumeratorType(this TypeSymbol type, CSharpCompilation compilation)
{
if (!(type is NamedTypeSymbol { Arity: 1 } namedType))
{
return false;
}
return (object)namedType.ConstructedFrom == compilation.GetWellKnownType(WellKnownType.System_Collections_Generic_IAsyncEnumerator_T);
}
/// <summary>
/// Returns true if the type is generic or non-generic custom task-like type due to the
/// [AsyncMethodBuilder(typeof(B))] attribute. It returns the "B".
/// </summary>
/// <remarks>
/// For the Task types themselves, this method might return true or false depending on mscorlib.
/// The definition of "custom task-like type" is one that has an [AsyncMethodBuilder(typeof(B))] attribute,
/// no more, no less. Validation of builder type B is left for elsewhere. This method returns B
/// without validation of any kind.
/// </remarks>
internal static bool IsCustomTaskType(this NamedTypeSymbol type, [NotNullWhen(true)] out object? builderArgument)
{
RoslynDebug.Assert((object)type != null);
var arity = type.Arity;
if (arity < 2)
{
return type.HasAsyncMethodBuilderAttribute(out builderArgument);
}
builderArgument = null;
return false;
}
/// <summary>
/// Replace Task-like types with Task types.
/// </summary>
internal static TypeSymbol NormalizeTaskTypes(this TypeSymbol type, CSharpCompilation compilation)
{
NormalizeTaskTypesInType(compilation, ref type);
return type;
}
/// <summary>
/// Replace Task-like types with Task types. Returns true if there were changes.
/// </summary>
private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeSymbol type)
{
switch (type.Kind)
{
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
{
var namedType = (NamedTypeSymbol)type;
var changed = NormalizeTaskTypesInNamedType(compilation, ref namedType);
type = namedType;
return changed;
}
case SymbolKind.ArrayType:
{
var arrayType = (ArrayTypeSymbol)type;
var changed = NormalizeTaskTypesInArray(compilation, ref arrayType);
type = arrayType;
return changed;
}
case SymbolKind.PointerType:
{
var pointerType = (PointerTypeSymbol)type;
var changed = NormalizeTaskTypesInPointer(compilation, ref pointerType);
type = pointerType;
return changed;
}
case SymbolKind.FunctionPointerType:
{
var functionPointerType = (FunctionPointerTypeSymbol)type;
var changed = NormalizeTaskTypesInFunctionPointer(compilation, ref functionPointerType);
type = functionPointerType;
return changed;
}
}
return false;
}
private static bool NormalizeTaskTypesInType(CSharpCompilation compilation, ref TypeWithAnnotations typeWithAnnotations)
{
var type = typeWithAnnotations.Type;
if (NormalizeTaskTypesInType(compilation, ref type))
{
typeWithAnnotations = TypeWithAnnotations.Create(type, customModifiers: typeWithAnnotations.CustomModifiers);
return true;
}
return false;
}
private static bool NormalizeTaskTypesInNamedType(CSharpCompilation compilation, ref NamedTypeSymbol type)
{
bool hasChanged = false;
if (!type.IsDefinition)
{
RoslynDebug.Assert(type.IsGenericType);
var typeArgumentsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance();
var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded;
type.GetAllTypeArguments(typeArgumentsBuilder, ref discardedUseSiteInfo);
for (int i = 0; i < typeArgumentsBuilder.Count; i++)
{
var typeWithModifier = typeArgumentsBuilder[i];
var typeArgNormalized = typeWithModifier.Type;
if (NormalizeTaskTypesInType(compilation, ref typeArgNormalized))
{
hasChanged = true;
// Preserve custom modifiers but without normalizing those types.
typeArgumentsBuilder[i] = TypeWithAnnotations.Create(typeArgNormalized, customModifiers: typeWithModifier.CustomModifiers);
}
}
if (hasChanged)
{
var originalType = type;
var originalDefinition = originalType.OriginalDefinition;
var typeParameters = originalDefinition.GetAllTypeParameters();
var typeMap = new TypeMap(typeParameters, typeArgumentsBuilder.ToImmutable(), allowAlpha: true);
type = typeMap.SubstituteNamedType(originalDefinition).WithTupleDataFrom(originalType);
}
typeArgumentsBuilder.Free();
}
if (type.OriginalDefinition.IsCustomTaskType(builderArgument: out _))
{
int arity = type.Arity;
RoslynDebug.Assert(arity < 2);
var taskType = compilation.GetWellKnownType(
arity == 0 ?
WellKnownType.System_Threading_Tasks_Task :
WellKnownType.System_Threading_Tasks_Task_T);
if (taskType.TypeKind == TypeKind.Error)
{
// Skip if Task types are not available.
return false;
}
type = arity == 0 ?
taskType :
taskType.Construct(
ImmutableArray.Create(type.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]),
unbound: false);
hasChanged = true;
}
return hasChanged;
}
private static bool NormalizeTaskTypesInArray(CSharpCompilation compilation, ref ArrayTypeSymbol arrayType)
{
var elementType = arrayType.ElementTypeWithAnnotations;
if (!NormalizeTaskTypesInType(compilation, ref elementType))
{
return false;
}
arrayType = arrayType.WithElementType(elementType);
return true;
}
private static bool NormalizeTaskTypesInPointer(CSharpCompilation compilation, ref PointerTypeSymbol pointerType)
{
var pointedAtType = pointerType.PointedAtTypeWithAnnotations;
if (!NormalizeTaskTypesInType(compilation, ref pointedAtType))
{
return false;
}
// Preserve custom modifiers but without normalizing those types.
pointerType = new PointerTypeSymbol(pointedAtType);
return true;
}
private static bool NormalizeTaskTypesInFunctionPointer(CSharpCompilation compilation, ref FunctionPointerTypeSymbol funcPtrType)
{
var returnType = funcPtrType.Signature.ReturnTypeWithAnnotations;
var madeChanges = NormalizeTaskTypesInType(compilation, ref returnType);
var paramTypes = ImmutableArray<TypeWithAnnotations>.Empty;
if (funcPtrType.Signature.ParameterCount > 0)
{
var paramsBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(funcPtrType.Signature.ParameterCount);
bool madeParamChanges = false;
foreach (var param in funcPtrType.Signature.Parameters)
{
var paramType = param.TypeWithAnnotations;
madeParamChanges |= NormalizeTaskTypesInType(compilation, ref paramType);
paramsBuilder.Add(paramType);
}
if (madeParamChanges)
{
madeChanges = true;
paramTypes = paramsBuilder.ToImmutableAndFree();
}
else
{
paramTypes = funcPtrType.Signature.ParameterTypesWithAnnotations;
paramsBuilder.Free();
}
}
if (madeChanges)
{
funcPtrType = funcPtrType.SubstituteTypeSymbol(returnType, paramTypes, refCustomModifiers: default, paramRefCustomModifiers: default);
return true;
}
else
{
return false;
}
}
internal static Cci.TypeReferenceWithAttributes GetTypeRefWithAttributes(
this TypeWithAnnotations type,
Emit.PEModuleBuilder moduleBuilder,
Symbol declaringSymbol,
Cci.ITypeReference typeRef)
{
var builder = ArrayBuilder<Cci.ICustomAttribute>.GetInstance();
var compilation = declaringSymbol.DeclaringCompilation;
if (compilation != null)
{
if (type.Type.ContainsTupleNames())
{
addIfNotNull(builder, compilation.SynthesizeTupleNamesAttribute(type.Type));
}
if (type.Type.ContainsNativeInteger())
{
addIfNotNull(builder, moduleBuilder.SynthesizeNativeIntegerAttribute(declaringSymbol, type.Type));
}
if (compilation.ShouldEmitNullableAttributes(declaringSymbol))
{
addIfNotNull(builder, moduleBuilder.SynthesizeNullableAttributeIfNecessary(declaringSymbol, declaringSymbol.GetNullableContextValue(), type));
}
static void addIfNotNull(ArrayBuilder<Cci.ICustomAttribute> builder, SynthesizedAttributeData? attr)
{
if (attr != null)
{
builder.Add(attr);
}
}
}
return new Cci.TypeReferenceWithAttributes(typeRef, builder.ToImmutableAndFree());
}
internal static bool IsWellKnownTypeInAttribute(this TypeSymbol typeSymbol)
=> typeSymbol.IsWellKnownInteropServicesTopLevelType("InAttribute");
internal static bool IsWellKnownTypeUnmanagedType(this TypeSymbol typeSymbol)
=> typeSymbol.IsWellKnownInteropServicesTopLevelType("UnmanagedType");
internal static bool IsWellKnownTypeIsExternalInit(this TypeSymbol typeSymbol)
=> typeSymbol.IsWellKnownCompilerServicesTopLevelType("IsExternalInit");
internal static bool IsWellKnownTypeOutAttribute(this TypeSymbol typeSymbol) => typeSymbol.IsWellKnownInteropServicesTopLevelType("OutAttribute");
private static bool IsWellKnownInteropServicesTopLevelType(this TypeSymbol typeSymbol, string name)
{
if (typeSymbol.Name != name || typeSymbol.ContainingType is object)
{
return false;
}
return IsContainedInNamespace(typeSymbol, "System", "Runtime", "InteropServices");
}
private static bool IsWellKnownCompilerServicesTopLevelType(this TypeSymbol typeSymbol, string name)
{
if (typeSymbol.Name != name)
{
return false;
}
return IsCompilerServicesTopLevelType(typeSymbol);
}
internal static bool IsCompilerServicesTopLevelType(this TypeSymbol typeSymbol)
=> typeSymbol.ContainingType is null && IsContainedInNamespace(typeSymbol, "System", "Runtime", "CompilerServices");
private static bool IsContainedInNamespace(this TypeSymbol typeSymbol, string outerNS, string midNS, string innerNS)
{
var innerNamespace = typeSymbol.ContainingNamespace;
if (innerNamespace?.Name != innerNS)
{
return false;
}
var midNamespace = innerNamespace.ContainingNamespace;
if (midNamespace?.Name != midNS)
{
return false;
}
var outerNamespace = midNamespace.ContainingNamespace;
if (outerNamespace?.Name != outerNS)
{
return false;
}
var globalNamespace = outerNamespace.ContainingNamespace;
return globalNamespace != null && globalNamespace.IsGlobalNamespace;
}
internal static int TypeToIndex(this TypeSymbol type)
{
switch (type.GetSpecialTypeSafe())
{
case SpecialType.System_Object: return 0;
case SpecialType.System_String: return 1;
case SpecialType.System_Boolean: return 2;
case SpecialType.System_Char: return 3;
case SpecialType.System_SByte: return 4;
case SpecialType.System_Int16: return 5;
case SpecialType.System_Int32: return 6;
case SpecialType.System_Int64: return 7;
case SpecialType.System_Byte: return 8;
case SpecialType.System_UInt16: return 9;
case SpecialType.System_UInt32: return 10;
case SpecialType.System_UInt64: return 11;
case SpecialType.System_IntPtr when type.IsNativeIntegerType: return 12;
case SpecialType.System_UIntPtr when type.IsNativeIntegerType: return 13;
case SpecialType.System_Single: return 14;
case SpecialType.System_Double: return 15;
case SpecialType.System_Decimal: return 16;
case SpecialType.None:
if ((object)type != null && type.IsNullableType())
{
TypeSymbol underlyingType = type.GetNullableUnderlyingType();
switch (underlyingType.GetSpecialTypeSafe())
{
case SpecialType.System_Boolean: return 17;
case SpecialType.System_Char: return 18;
case SpecialType.System_SByte: return 19;
case SpecialType.System_Int16: return 20;
case SpecialType.System_Int32: return 21;
case SpecialType.System_Int64: return 22;
case SpecialType.System_Byte: return 23;
case SpecialType.System_UInt16: return 24;
case SpecialType.System_UInt32: return 25;
case SpecialType.System_UInt64: return 26;
case SpecialType.System_IntPtr when underlyingType.IsNativeIntegerType: return 27;
case SpecialType.System_UIntPtr when underlyingType.IsNativeIntegerType: return 28;
case SpecialType.System_Single: return 29;
case SpecialType.System_Double: return 30;
case SpecialType.System_Decimal: return 31;
}
}
// fall through
goto default;
default: return -1;
}
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmGetChildrenAsyncResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
namespace Microsoft.VisualStudio.Debugger.Evaluation
{
public struct DkmGetChildrenAsyncResult
{
public DkmGetChildrenAsyncResult(DkmEvaluationResult[] InitialChildren, DkmEvaluationResultEnumContext EnumContext)
: this()
{
if (InitialChildren == null)
{
throw new ArgumentNullException();
}
this.InitialChildren = InitialChildren;
this.EnumContext = EnumContext;
}
public DkmEvaluationResultEnumContext EnumContext { get; }
public DkmEvaluationResult[] InitialChildren { get; }
internal Exception Exception { get; set; }
public static DkmGetChildrenAsyncResult CreateErrorResult(Exception exception)
{
return new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], EnumContext: null) { Exception = exception };
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
#region Assembly Microsoft.VisualStudio.Debugger.Engine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
// References\Debugger\v2.0\Microsoft.VisualStudio.Debugger.Engine.dll
#endregion
using System;
namespace Microsoft.VisualStudio.Debugger.Evaluation
{
public struct DkmGetChildrenAsyncResult
{
public DkmGetChildrenAsyncResult(DkmEvaluationResult[] InitialChildren, DkmEvaluationResultEnumContext EnumContext)
: this()
{
if (InitialChildren == null)
{
throw new ArgumentNullException();
}
this.InitialChildren = InitialChildren;
this.EnumContext = EnumContext;
}
public DkmEvaluationResultEnumContext EnumContext { get; }
public DkmEvaluationResult[] InitialChildren { get; }
internal Exception Exception { get; set; }
public static DkmGetChildrenAsyncResult CreateErrorResult(Exception exception)
{
return new DkmGetChildrenAsyncResult(new DkmEvaluationResult[0], EnumContext: null) { Exception = exception };
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/CSharp/Portable/Syntax/InternalSyntax/SyntaxTrivia.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal class SyntaxTrivia : CSharpSyntaxNode
{
public readonly string Text;
internal SyntaxTrivia(SyntaxKind kind, string text, DiagnosticInfo[]? diagnostics = null, SyntaxAnnotation[]? annotations = null)
: base(kind, diagnostics, annotations, text.Length)
{
this.Text = text;
if (kind == SyntaxKind.PreprocessingMessageTrivia)
{
this.flags |= NodeFlags.ContainsSkippedText;
}
}
internal SyntaxTrivia(ObjectReader reader)
: base(reader)
{
this.Text = reader.ReadString();
this.FullWidth = this.Text.Length;
}
static SyntaxTrivia()
{
ObjectBinder.RegisterTypeReader(typeof(SyntaxTrivia), r => new SyntaxTrivia(r));
}
public override bool IsTrivia => true;
internal override bool ShouldReuseInSerialization => this.Kind == SyntaxKind.WhitespaceTrivia &&
FullWidth < Lexer.MaxCachedTokenSize;
internal override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteString(this.Text);
}
internal static SyntaxTrivia Create(SyntaxKind kind, string text)
{
return new SyntaxTrivia(kind, text);
}
public override string ToFullString()
{
return this.Text;
}
public override string ToString()
{
return this.Text;
}
internal override GreenNode GetSlot(int index)
{
throw ExceptionUtilities.Unreachable;
}
public override int Width
{
get
{
Debug.Assert(this.FullWidth == this.Text.Length);
return this.FullWidth;
}
}
public override int GetLeadingTriviaWidth()
{
return 0;
}
public override int GetTrailingTriviaWidth()
{
return 0;
}
internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics)
{
return new SyntaxTrivia(this.Kind, this.Text, diagnostics, GetAnnotations());
}
internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations)
{
return new SyntaxTrivia(this.Kind, this.Text, GetDiagnostics(), annotations);
}
public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor)
{
return visitor.VisitTrivia(this);
}
public override void Accept(CSharpSyntaxVisitor visitor)
{
visitor.VisitTrivia(this);
}
protected override void WriteTriviaTo(System.IO.TextWriter writer)
{
writer.Write(Text);
}
public static implicit operator CodeAnalysis.SyntaxTrivia(SyntaxTrivia trivia)
{
return new CodeAnalysis.SyntaxTrivia(token: default, trivia, position: 0, index: 0);
}
public override bool IsEquivalentTo(GreenNode? other)
{
if (!base.IsEquivalentTo(other))
{
return false;
}
if (this.Text != ((SyntaxTrivia)other).Text)
{
return false;
}
return true;
}
internal override SyntaxNode CreateRed(SyntaxNode? parent, int position)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax
{
internal class SyntaxTrivia : CSharpSyntaxNode
{
public readonly string Text;
internal SyntaxTrivia(SyntaxKind kind, string text, DiagnosticInfo[]? diagnostics = null, SyntaxAnnotation[]? annotations = null)
: base(kind, diagnostics, annotations, text.Length)
{
this.Text = text;
if (kind == SyntaxKind.PreprocessingMessageTrivia)
{
this.flags |= NodeFlags.ContainsSkippedText;
}
}
internal SyntaxTrivia(ObjectReader reader)
: base(reader)
{
this.Text = reader.ReadString();
this.FullWidth = this.Text.Length;
}
static SyntaxTrivia()
{
ObjectBinder.RegisterTypeReader(typeof(SyntaxTrivia), r => new SyntaxTrivia(r));
}
public override bool IsTrivia => true;
internal override bool ShouldReuseInSerialization => this.Kind == SyntaxKind.WhitespaceTrivia &&
FullWidth < Lexer.MaxCachedTokenSize;
internal override void WriteTo(ObjectWriter writer)
{
base.WriteTo(writer);
writer.WriteString(this.Text);
}
internal static SyntaxTrivia Create(SyntaxKind kind, string text)
{
return new SyntaxTrivia(kind, text);
}
public override string ToFullString()
{
return this.Text;
}
public override string ToString()
{
return this.Text;
}
internal override GreenNode GetSlot(int index)
{
throw ExceptionUtilities.Unreachable;
}
public override int Width
{
get
{
Debug.Assert(this.FullWidth == this.Text.Length);
return this.FullWidth;
}
}
public override int GetLeadingTriviaWidth()
{
return 0;
}
public override int GetTrailingTriviaWidth()
{
return 0;
}
internal override GreenNode SetDiagnostics(DiagnosticInfo[]? diagnostics)
{
return new SyntaxTrivia(this.Kind, this.Text, diagnostics, GetAnnotations());
}
internal override GreenNode SetAnnotations(SyntaxAnnotation[]? annotations)
{
return new SyntaxTrivia(this.Kind, this.Text, GetDiagnostics(), annotations);
}
public override TResult Accept<TResult>(CSharpSyntaxVisitor<TResult> visitor)
{
return visitor.VisitTrivia(this);
}
public override void Accept(CSharpSyntaxVisitor visitor)
{
visitor.VisitTrivia(this);
}
protected override void WriteTriviaTo(System.IO.TextWriter writer)
{
writer.Write(Text);
}
public static implicit operator CodeAnalysis.SyntaxTrivia(SyntaxTrivia trivia)
{
return new CodeAnalysis.SyntaxTrivia(token: default, trivia, position: 0, index: 0);
}
public override bool IsEquivalentTo(GreenNode? other)
{
if (!base.IsEquivalentTo(other))
{
return false;
}
if (this.Text != ((SyntaxTrivia)other).Text)
{
return false;
}
return true;
}
internal override SyntaxNode CreateRed(SyntaxNode? parent, int position)
{
throw ExceptionUtilities.Unreachable;
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/VisualBasicTest/ConvertToInterpolatedString/ConvertPlaceholderToInterpolatedStringTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertToInterpolatedString
Public Class ConvertPlaceholderToInterpolatedStringTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertPlaceholderToInterpolatedStringRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestSingleItemSubstitution() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}", 1)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOrdering() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{1}{2}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }{2 }{3 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOrdering2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{2}{1}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }{3 }{2 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOrdering3() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{0}{0}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }{1 }{1 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOutsideRange() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{4}{5}{6}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{4}{5}{6}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemDoNotHaveCast() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{1}{2}", 0.5, "Hello", 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{0.5 }{"Hello" }{3 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemWithoutSyntaxErrorDoesNotHaveCast() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{1}{2}", 0.5, "Hello", 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{0.5 }{"Hello" }{3 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestPreserveParenthesis() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}", (New Object))|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{(New Object) }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMultiLineExpression() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}", If(True,
"Yes",
TryCast(False, Object)))|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{If(True, "Yes", TryCast(False, Object)) }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim pricePerOunce As Decimal = 17.36
Dim s = [|String.Format("The current price Is {0:C2} per ounce.",
pricePerOunce)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim pricePerOunce As Decimal = 17.36
Dim s = $"The current price Is {pricePerOunce:C2} per ounce."
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim s = [|String.Format("It Is now {0:d} at {0:T}", DateTime.Now)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim s = $"It Is now {DateTime.Now:d} at {DateTime.Now:T}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers3() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim years As Integer() = {2013, 2014, 2015}
Dim population As Integer() = {1025632, 1105967, 1148203}
Dim s = String.Format("{0,6} {1,15}\n\n", "Year", "Population")
For index = 0 To years.Length - 1
s += [|String.Format("{0, 6} {1, 15: N0}\n",
years(index), population(index))|]
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim years As Integer() = {2013, 2014, 2015}
Dim population As Integer() = {1025632, 1105967, 1148203}
Dim s = String.Format("{0,6} {1,15}\n\n", "Year", "Population")
For index = 0 To years.Length - 1
s += $"{years(index), 6} {population(index), 15: N0}\n"
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers4() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim s = [|String.Format("{0,-10:C}", 126347.89)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim s = $"{126347.89,-10:C}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers5() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim cities As Tuple(Of String, DateTime, Integer, DateTime, Integer)() =
{Tuple.Create("Los Angeles", New DateTime(1940, 1, 1), 1504277,
New DateTime(1950, 1, 1), 1970358),
Tuple.Create("New York", New DateTime(1940, 1, 1), 7454995,
New DateTime(1950, 1, 1), 7891957),
Tuple.Create("Chicago", New DateTime(1940, 1, 1), 3396808,
New DateTime(1950, 1, 1), 3620962),
Tuple.Create("Detroit", New DateTime(1940, 1, 1), 1623452,
New DateTime(1950, 1, 1), 1849568)}
Dim output As String
For Each city In cities
output = [|String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3) / CType(city.Item3, Double))|]
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim cities As Tuple(Of String, DateTime, Integer, DateTime, Integer)() =
{Tuple.Create("Los Angeles", New DateTime(1940, 1, 1), 1504277,
New DateTime(1950, 1, 1), 1970358),
Tuple.Create("New York", New DateTime(1940, 1, 1), 7454995,
New DateTime(1950, 1, 1), 7891957),
Tuple.Create("Chicago", New DateTime(1940, 1, 1), 3396808,
New DateTime(1950, 1, 1), 3620962),
Tuple.Create("Detroit", New DateTime(1940, 1, 1), 1623452,
New DateTime(1950, 1, 1), 1849568)}
Dim output As String
For Each city In cities
output = $"{city.Item1,-12}{city.Item2,8:yyyy}{city.Item3,12:N0}{city.Item4,8:yyyy}{city.Item5,12:N0}{(city.Item5 - city.Item3) / CType(city.Item3, Double),14:P1}"
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers6() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim values As Short() = {Int16.MaxValue, -27, 0, 1042, Int16.MaxValue}
For Each value In values
Dim s = [|String.Format("{0,10:G}: {0,10:X}", value)|]
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim values As Short() = {Int16.MaxValue, -27, 0, 1042, Int16.MaxValue}
For Each value In values
Dim s = $"{value,10:G}: {value,10:X}"
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMultilineStringLiteral2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim value1 = 16932
Dim value2 = 15421
Dim result = [|String.Format("
{0,10} ({0,8:X8})
And {1,10} ({1,8:X8})
= {2,10} ({2,8:X8})",
value1, value2, value1 And value2)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim value1 = 16932
Dim value2 = 15421
Dim result = $"
{value1,10} ({value1,8:X8})
And {value2,10} ({value2,8:X8})
= {value1 And value2,10} ({value1 And value2,8:X8})"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestParamsArray() As Task
Dim text = <File>
Imports System
Module T
Sub M(args As String())
Dim s = [|String.Format("{0}", args)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestMissingInRegularAndScriptAsync(text)
End Function
<WorkItem(13605, "https://github.com/dotnet/roslyn/issues/13605")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestInvocationWithNullArguments() As Task
Dim text =
"Module Module1
Sub Main()
[|TaskAwaiter|]
End Sub
End Module"
Await TestMissingInRegularAndScriptAsync(text)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments1() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format(arg0:="test", arg1:="also", format:="This {0} {1} works")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"This {"test" } {"also" } works"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("This {0} {1} works", arg0:="test", arg1:="also")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"This {"test" } {"also" } works"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments3() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2}", "10", arg1:="11", arg2:="12")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments4() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2}", "10", arg2:="12", arg1:="11")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments5() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2} {3}", "10", arg1:="11", arg2:="12")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" } {3}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments_CaseInsensitive() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2}", ARg0:="10", aRg1:="11", Arg2:="12")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
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
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertToInterpolatedString
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertToInterpolatedString
Public Class ConvertPlaceholderToInterpolatedStringTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertPlaceholderToInterpolatedStringRefactoringProvider()
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestSingleItemSubstitution() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}", 1)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOrdering() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{1}{2}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }{2 }{3 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOrdering2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{2}{1}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }{3 }{2 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOrdering3() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{0}{0}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{1 }{1 }{1 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemOutsideRange() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{4}{5}{6}", 1, 2, 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{4}{5}{6}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemDoNotHaveCast() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{1}{2}", 0.5, "Hello", 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{0.5 }{"Hello" }{3 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestItemWithoutSyntaxErrorDoesNotHaveCast() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}{1}{2}", 0.5, "Hello", 3)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{0.5 }{"Hello" }{3 }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestPreserveParenthesis() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}", (New Object))|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{(New Object) }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMultiLineExpression() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0}", If(True,
"Yes",
TryCast(False, Object)))|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{If(True, "Yes", TryCast(False, Object)) }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim pricePerOunce As Decimal = 17.36
Dim s = [|String.Format("The current price Is {0:C2} per ounce.",
pricePerOunce)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim pricePerOunce As Decimal = 17.36
Dim s = $"The current price Is {pricePerOunce:C2} per ounce."
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim s = [|String.Format("It Is now {0:d} at {0:T}", DateTime.Now)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim s = $"It Is now {DateTime.Now:d} at {DateTime.Now:T}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers3() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim years As Integer() = {2013, 2014, 2015}
Dim population As Integer() = {1025632, 1105967, 1148203}
Dim s = String.Format("{0,6} {1,15}\n\n", "Year", "Population")
For index = 0 To years.Length - 1
s += [|String.Format("{0, 6} {1, 15: N0}\n",
years(index), population(index))|]
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim years As Integer() = {2013, 2014, 2015}
Dim population As Integer() = {1025632, 1105967, 1148203}
Dim s = String.Format("{0,6} {1,15}\n\n", "Year", "Population")
For index = 0 To years.Length - 1
s += $"{years(index), 6} {population(index), 15: N0}\n"
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers4() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim s = [|String.Format("{0,-10:C}", 126347.89)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim s = $"{126347.89,-10:C}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers5() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim cities As Tuple(Of String, DateTime, Integer, DateTime, Integer)() =
{Tuple.Create("Los Angeles", New DateTime(1940, 1, 1), 1504277,
New DateTime(1950, 1, 1), 1970358),
Tuple.Create("New York", New DateTime(1940, 1, 1), 7454995,
New DateTime(1950, 1, 1), 7891957),
Tuple.Create("Chicago", New DateTime(1940, 1, 1), 3396808,
New DateTime(1950, 1, 1), 3620962),
Tuple.Create("Detroit", New DateTime(1940, 1, 1), 1623452,
New DateTime(1950, 1, 1), 1849568)}
Dim output As String
For Each city In cities
output = [|String.Format("{0,-12}{1,8:yyyy}{2,12:N0}{3,8:yyyy}{4,12:N0}{5,14:P1}",
city.Item1, city.Item2, city.Item3, city.Item4, city.Item5,
(city.Item5 - city.Item3) / CType(city.Item3, Double))|]
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim cities As Tuple(Of String, DateTime, Integer, DateTime, Integer)() =
{Tuple.Create("Los Angeles", New DateTime(1940, 1, 1), 1504277,
New DateTime(1950, 1, 1), 1970358),
Tuple.Create("New York", New DateTime(1940, 1, 1), 7454995,
New DateTime(1950, 1, 1), 7891957),
Tuple.Create("Chicago", New DateTime(1940, 1, 1), 3396808,
New DateTime(1950, 1, 1), 3620962),
Tuple.Create("Detroit", New DateTime(1940, 1, 1), 1623452,
New DateTime(1950, 1, 1), 1849568)}
Dim output As String
For Each city In cities
output = $"{city.Item1,-12}{city.Item2,8:yyyy}{city.Item3,12:N0}{city.Item4,8:yyyy}{city.Item5,12:N0}{(city.Item5 - city.Item3) / CType(city.Item3, Double),14:P1}"
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatSpecifiers6() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim values As Short() = {Int16.MaxValue, -27, 0, 1042, Int16.MaxValue}
For Each value In values
Dim s = [|String.Format("{0,10:G}: {0,10:X}", value)|]
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim values As Short() = {Int16.MaxValue, -27, 0, 1042, Int16.MaxValue}
For Each value In values
Dim s = $"{value,10:G}: {value,10:X}"
Next
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestMultilineStringLiteral2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim value1 = 16932
Dim value2 = 15421
Dim result = [|String.Format("
{0,10} ({0,8:X8})
And {1,10} ({1,8:X8})
= {2,10} ({2,8:X8})",
value1, value2, value1 And value2)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim value1 = 16932
Dim value2 = 15421
Dim result = $"
{value1,10} ({value1,8:X8})
And {value2,10} ({value2,8:X8})
= {value1 And value2,10} ({value1 And value2,8:X8})"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestParamsArray() As Task
Dim text = <File>
Imports System
Module T
Sub M(args As String())
Dim s = [|String.Format("{0}", args)|]
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestMissingInRegularAndScriptAsync(text)
End Function
<WorkItem(13605, "https://github.com/dotnet/roslyn/issues/13605")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestInvocationWithNullArguments() As Task
Dim text =
"Module Module1
Sub Main()
[|TaskAwaiter|]
End Sub
End Module"
Await TestMissingInRegularAndScriptAsync(text)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments1() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format(arg0:="test", arg1:="also", format:="This {0} {1} works")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"This {"test" } {"also" } works"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments2() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("This {0} {1} works", arg0:="test", arg1:="also")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"This {"test" } {"also" } works"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments3() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2}", "10", arg1:="11", arg2:="12")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments4() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2}", "10", arg2:="12", arg1:="11")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments5() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2} {3}", "10", arg1:="11", arg2:="12")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" } {3}"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
<WorkItem(19162, "https://github.com/dotnet/roslyn/issues/19162")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertToInterpolatedString)>
Public Async Function TestFormatWithNamedArguments_CaseInsensitive() As Task
Dim text = <File>
Imports System
Module T
Sub M()
Dim a = [|String.Format("{0} {1} {2}", ARg0:="10", aRg1:="11", Arg2:="12")|]
End Sub
End Module</File>.ConvertTestSourceTag()
Dim expected = <File>
Imports System
Module T
Sub M()
Dim a = $"{"10" } {"11" } {"12" }"
End Sub
End Module</File>.ConvertTestSourceTag()
Await TestInRegularAndScriptAsync(text, expected)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/EditorFeatures/Core/Implementation/Classification/ClassificationTypeDefinitions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification
{
internal sealed class ClassificationTypeDefinitions
{
#region Preprocessor Text
[Export]
[Name(ClassificationTypeNames.PreprocessorText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal ClassificationTypeDefinition PreprocessorTextTypeDefinition { get; set; }
#endregion
#region Punctuation
[Export]
[Name(ClassificationTypeNames.Punctuation)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal ClassificationTypeDefinition PunctuationTypeDefinition;
#endregion
#region String - Verbatim
[Export]
[Name(ClassificationTypeNames.VerbatimStringLiteral)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition StringVerbatimTypeDefinition;
[Export]
[Name(ClassificationTypeNames.StringEscapeCharacter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition StringEscapeCharacterTypeDefinition;
#endregion
#region Keyword - Control
// Keyword - Control sets its BaseDefinitions to be Keyword so that
// in the absence of specific styling they will appear as keywords.
[Export]
[Name(ClassificationTypeNames.ControlKeyword)]
[BaseDefinition(PredefinedClassificationTypeNames.Keyword)]
internal ClassificationTypeDefinition ControlKeywordTypeDefinition;
#endregion
#region User Types - Classes
[Export]
[Name(ClassificationTypeNames.ClassName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeClassesTypeDefinition;
#endregion
#region User Types - Records
[Export]
[Name(ClassificationTypeNames.RecordClassName)]
[BaseDefinition(ClassificationTypeNames.ClassName)]
internal readonly ClassificationTypeDefinition UserTypeRecordsTypeDefinition;
#endregion
#region User Types - Record Structs
[Export]
[Name(ClassificationTypeNames.RecordStructName)]
[BaseDefinition(ClassificationTypeNames.StructName)]
internal readonly ClassificationTypeDefinition UserTypeRecordStructsTypeDefinition;
#endregion
#region User Types - Delegates
[Export]
[Name(ClassificationTypeNames.DelegateName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeDelegatesTypeDefinition;
#endregion
#region User Types - Enums
[Export]
[Name(ClassificationTypeNames.EnumName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeEnumsTypeDefinition;
#endregion
#region User Types - Interfaces
[Export]
[Name(ClassificationTypeNames.InterfaceName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeInterfacesTypeDefinition;
#endregion
#region User Types - Modules
[Export]
[Name(ClassificationTypeNames.ModuleName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeModulesTypeDefinition;
#endregion
#region User Types - Structures
[Export]
[Name(ClassificationTypeNames.StructName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeStructuresTypeDefinition;
#endregion
#region User Types - Type Parameters
[Export]
[Name(ClassificationTypeNames.TypeParameterName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeTypeParametersTypeDefinition;
#endregion
// User Members - * set their BaseDefinitions to be Identifier so that
// in the absence of specific styling they will appear as identifiers.
// Extension Methods are an exception and their base definition is Method
// since it is a more specific type of method.
#region User Members - Fields
[Export]
[Name(ClassificationTypeNames.FieldName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersFieldsTypeDefinition;
#endregion
#region User Members - Enum Memberd
[Export]
[Name(ClassificationTypeNames.EnumMemberName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersEnumMembersTypeDefinition;
#endregion
#region User Members - Constants
[Export]
[Name(ClassificationTypeNames.ConstantName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersConstantsTypeDefinition;
#endregion
#region User Members - Locals
[Export]
[Name(ClassificationTypeNames.LocalName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersLocalsTypeDefinition;
#endregion
#region User Members - Parameters
[Export]
[Name(ClassificationTypeNames.ParameterName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersParametersTypeDefinition;
#endregion
#region User Members - Methods
[Export]
[Name(ClassificationTypeNames.MethodName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersMethodsTypeDefinition;
#endregion
#region User Members - Extension Methods
[Export]
[Name(ClassificationTypeNames.ExtensionMethodName)]
[BaseDefinition(ClassificationTypeNames.MethodName)]
internal readonly ClassificationTypeDefinition UserMembersExtensionMethodsTypeDefinition;
#endregion
#region User Members - Properties
[Export]
[Name(ClassificationTypeNames.PropertyName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersPropertiesTypeDefinition;
#endregion
#region User Members - Events
[Export]
[Name(ClassificationTypeNames.EventName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersEventsTypeDefinition;
#endregion
#region User Members - Namespaces
[Export]
[Name(ClassificationTypeNames.NamespaceName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersNamespacesTypeDefinition;
#endregion
#region User Members - Labels
[Export]
[Name(ClassificationTypeNames.LabelName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersLabelsTypeDefinition;
#endregion
#region XML Doc Comments - Attribute Name
[Export]
[Name(ClassificationTypeNames.XmlDocCommentAttributeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentAttributeNameTypeDefinition;
#endregion
#region XML Doc Comments - Attribute Quotes
[Export]
[Name(ClassificationTypeNames.XmlDocCommentAttributeQuotes)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentAttributeQuotesTypeDefinition;
#endregion
#region XML Doc Comments - Attribute Value
[Export]
[Name(ClassificationTypeNames.XmlDocCommentAttributeValue)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentAttributeValueTypeDefinition;
#endregion
#region XML Doc Comments - CData Section
[Export]
[Name(ClassificationTypeNames.XmlDocCommentCDataSection)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentCDataSectionTypeDefinition;
#endregion
#region XML Doc Comments - Comment
[Export]
[Name(ClassificationTypeNames.XmlDocCommentComment)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentCommentTypeDefinition;
#endregion
#region XML Doc Comments - Delimiter
[Export]
[Name(ClassificationTypeNames.XmlDocCommentDelimiter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentDelimiterTypeDefinition;
#endregion
#region XML Doc Comments - Entity Reference
[Export]
[Name(ClassificationTypeNames.XmlDocCommentEntityReference)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentEntityReferenceTypeDefinition;
#endregion
#region XML Doc Comments - Name
[Export]
[Name(ClassificationTypeNames.XmlDocCommentName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentNameTypeDefinition;
#endregion
#region XML Doc Comments - Processing Instruction
[Export]
[Name(ClassificationTypeNames.XmlDocCommentProcessingInstruction)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentProcessingInstructionTypeDefinition;
#endregion
#region XML Doc Comments - Text
[Export]
[Name(ClassificationTypeNames.XmlDocCommentText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentTextTypeDefinition;
#endregion
#region Regex
[Export]
[Name(ClassificationTypeNames.RegexComment)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexCommentTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexTextTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexCharacterClass)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexCharacterClassTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexQuantifier)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexQuantifierTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexAnchor)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexAnchorTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexAlternation)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexAlternationTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexOtherEscape)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexOtherEscapeTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexSelfEscapedCharacter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexSelfEscapedCharacterTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexGrouping)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexGroupingTypeDefinition;
#endregion
#region VB XML Literals - Attribute Name
[Export]
[Name(ClassificationTypeNames.XmlLiteralAttributeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralAttributeNameTypeDefinition;
#endregion
#region VB XML Literals - Attribute Quotes
[Export]
[Name(ClassificationTypeNames.XmlLiteralAttributeQuotes)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralAttributeQuotesTypeDefinition;
#endregion
#region VB XML Literals - Attribute Value
[Export]
[Name(ClassificationTypeNames.XmlLiteralAttributeValue)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralAttributeValueTypeDefinition;
#endregion
#region VB XML Literals - CData Section
[Export]
[Name(ClassificationTypeNames.XmlLiteralCDataSection)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralCDataSectionTypeDefinition;
#endregion
#region VB XML Literals - Comment
[Export]
[Name(ClassificationTypeNames.XmlLiteralComment)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralCommentTypeDefinition;
#endregion
#region VB XML Literals - Delimiter
[Export]
[Name(ClassificationTypeNames.XmlLiteralDelimiter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralDelimiterTypeDefinition;
#endregion
#region VB XML Literals - Embedded Expression
[Export]
[Name(ClassificationTypeNames.XmlLiteralEmbeddedExpression)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralEmbeddedExpressionTypeDefinition;
#endregion
#region VB XML Literals - Entity Reference
[Export]
[Name(ClassificationTypeNames.XmlLiteralEntityReference)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralEntityReferenceTypeDefinition;
#endregion
#region VB XML Literals - Name
[Export]
[Name(ClassificationTypeNames.XmlLiteralName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralNameTypeDefinition;
#endregion
#region VB XML Literals - Processing Instruction
[Export]
[Name(ClassificationTypeNames.XmlLiteralProcessingInstruction)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralProcessingInstructionTypeDefinition;
#endregion
#region VB XML Literals - Text
[Export]
[Name(ClassificationTypeNames.XmlLiteralText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralTextTypeDefinition;
#endregion
#region Reassigned Variable
[Export]
[Name(ClassificationTypeNames.ReassignedVariable)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition ReassignedVariableTypeDefinition;
#endregion
#region Static Symbol
[Export]
[Name(ClassificationTypeNames.StaticSymbol)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition StaticSymbolTypeDefinition;
#endregion
#region Operator - Overloaded
// Operator - Overloaded sets its BaseDefinitions to be Operator so that
// in the absence of specific styling they will appear as operators.
[Export]
[Name(ClassificationTypeNames.OperatorOverloaded)]
[BaseDefinition(PredefinedClassificationTypeNames.Operator)]
internal readonly ClassificationTypeDefinition OperatorOverloadTypeDefinition;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.VisualStudio.Language.StandardClassification;
using Microsoft.VisualStudio.Text.Classification;
using Microsoft.VisualStudio.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification
{
internal sealed class ClassificationTypeDefinitions
{
#region Preprocessor Text
[Export]
[Name(ClassificationTypeNames.PreprocessorText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal ClassificationTypeDefinition PreprocessorTextTypeDefinition { get; set; }
#endregion
#region Punctuation
[Export]
[Name(ClassificationTypeNames.Punctuation)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal ClassificationTypeDefinition PunctuationTypeDefinition;
#endregion
#region String - Verbatim
[Export]
[Name(ClassificationTypeNames.VerbatimStringLiteral)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition StringVerbatimTypeDefinition;
[Export]
[Name(ClassificationTypeNames.StringEscapeCharacter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition StringEscapeCharacterTypeDefinition;
#endregion
#region Keyword - Control
// Keyword - Control sets its BaseDefinitions to be Keyword so that
// in the absence of specific styling they will appear as keywords.
[Export]
[Name(ClassificationTypeNames.ControlKeyword)]
[BaseDefinition(PredefinedClassificationTypeNames.Keyword)]
internal ClassificationTypeDefinition ControlKeywordTypeDefinition;
#endregion
#region User Types - Classes
[Export]
[Name(ClassificationTypeNames.ClassName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeClassesTypeDefinition;
#endregion
#region User Types - Records
[Export]
[Name(ClassificationTypeNames.RecordClassName)]
[BaseDefinition(ClassificationTypeNames.ClassName)]
internal readonly ClassificationTypeDefinition UserTypeRecordsTypeDefinition;
#endregion
#region User Types - Record Structs
[Export]
[Name(ClassificationTypeNames.RecordStructName)]
[BaseDefinition(ClassificationTypeNames.StructName)]
internal readonly ClassificationTypeDefinition UserTypeRecordStructsTypeDefinition;
#endregion
#region User Types - Delegates
[Export]
[Name(ClassificationTypeNames.DelegateName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeDelegatesTypeDefinition;
#endregion
#region User Types - Enums
[Export]
[Name(ClassificationTypeNames.EnumName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeEnumsTypeDefinition;
#endregion
#region User Types - Interfaces
[Export]
[Name(ClassificationTypeNames.InterfaceName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeInterfacesTypeDefinition;
#endregion
#region User Types - Modules
[Export]
[Name(ClassificationTypeNames.ModuleName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeModulesTypeDefinition;
#endregion
#region User Types - Structures
[Export]
[Name(ClassificationTypeNames.StructName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeStructuresTypeDefinition;
#endregion
#region User Types - Type Parameters
[Export]
[Name(ClassificationTypeNames.TypeParameterName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition UserTypeTypeParametersTypeDefinition;
#endregion
// User Members - * set their BaseDefinitions to be Identifier so that
// in the absence of specific styling they will appear as identifiers.
// Extension Methods are an exception and their base definition is Method
// since it is a more specific type of method.
#region User Members - Fields
[Export]
[Name(ClassificationTypeNames.FieldName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersFieldsTypeDefinition;
#endregion
#region User Members - Enum Memberd
[Export]
[Name(ClassificationTypeNames.EnumMemberName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersEnumMembersTypeDefinition;
#endregion
#region User Members - Constants
[Export]
[Name(ClassificationTypeNames.ConstantName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersConstantsTypeDefinition;
#endregion
#region User Members - Locals
[Export]
[Name(ClassificationTypeNames.LocalName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersLocalsTypeDefinition;
#endregion
#region User Members - Parameters
[Export]
[Name(ClassificationTypeNames.ParameterName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersParametersTypeDefinition;
#endregion
#region User Members - Methods
[Export]
[Name(ClassificationTypeNames.MethodName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersMethodsTypeDefinition;
#endregion
#region User Members - Extension Methods
[Export]
[Name(ClassificationTypeNames.ExtensionMethodName)]
[BaseDefinition(ClassificationTypeNames.MethodName)]
internal readonly ClassificationTypeDefinition UserMembersExtensionMethodsTypeDefinition;
#endregion
#region User Members - Properties
[Export]
[Name(ClassificationTypeNames.PropertyName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersPropertiesTypeDefinition;
#endregion
#region User Members - Events
[Export]
[Name(ClassificationTypeNames.EventName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersEventsTypeDefinition;
#endregion
#region User Members - Namespaces
[Export]
[Name(ClassificationTypeNames.NamespaceName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersNamespacesTypeDefinition;
#endregion
#region User Members - Labels
[Export]
[Name(ClassificationTypeNames.LabelName)]
[BaseDefinition(PredefinedClassificationTypeNames.Identifier)]
internal readonly ClassificationTypeDefinition UserMembersLabelsTypeDefinition;
#endregion
#region XML Doc Comments - Attribute Name
[Export]
[Name(ClassificationTypeNames.XmlDocCommentAttributeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentAttributeNameTypeDefinition;
#endregion
#region XML Doc Comments - Attribute Quotes
[Export]
[Name(ClassificationTypeNames.XmlDocCommentAttributeQuotes)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentAttributeQuotesTypeDefinition;
#endregion
#region XML Doc Comments - Attribute Value
[Export]
[Name(ClassificationTypeNames.XmlDocCommentAttributeValue)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentAttributeValueTypeDefinition;
#endregion
#region XML Doc Comments - CData Section
[Export]
[Name(ClassificationTypeNames.XmlDocCommentCDataSection)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentCDataSectionTypeDefinition;
#endregion
#region XML Doc Comments - Comment
[Export]
[Name(ClassificationTypeNames.XmlDocCommentComment)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentCommentTypeDefinition;
#endregion
#region XML Doc Comments - Delimiter
[Export]
[Name(ClassificationTypeNames.XmlDocCommentDelimiter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentDelimiterTypeDefinition;
#endregion
#region XML Doc Comments - Entity Reference
[Export]
[Name(ClassificationTypeNames.XmlDocCommentEntityReference)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentEntityReferenceTypeDefinition;
#endregion
#region XML Doc Comments - Name
[Export]
[Name(ClassificationTypeNames.XmlDocCommentName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentNameTypeDefinition;
#endregion
#region XML Doc Comments - Processing Instruction
[Export]
[Name(ClassificationTypeNames.XmlDocCommentProcessingInstruction)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentProcessingInstructionTypeDefinition;
#endregion
#region XML Doc Comments - Text
[Export]
[Name(ClassificationTypeNames.XmlDocCommentText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlDocCommentTextTypeDefinition;
#endregion
#region Regex
[Export]
[Name(ClassificationTypeNames.RegexComment)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexCommentTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexTextTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexCharacterClass)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexCharacterClassTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexQuantifier)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexQuantifierTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexAnchor)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexAnchorTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexAlternation)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexAlternationTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexOtherEscape)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexOtherEscapeTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexSelfEscapedCharacter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexSelfEscapedCharacterTypeDefinition;
[Export]
[Name(ClassificationTypeNames.RegexGrouping)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition RegexGroupingTypeDefinition;
#endregion
#region VB XML Literals - Attribute Name
[Export]
[Name(ClassificationTypeNames.XmlLiteralAttributeName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralAttributeNameTypeDefinition;
#endregion
#region VB XML Literals - Attribute Quotes
[Export]
[Name(ClassificationTypeNames.XmlLiteralAttributeQuotes)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralAttributeQuotesTypeDefinition;
#endregion
#region VB XML Literals - Attribute Value
[Export]
[Name(ClassificationTypeNames.XmlLiteralAttributeValue)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralAttributeValueTypeDefinition;
#endregion
#region VB XML Literals - CData Section
[Export]
[Name(ClassificationTypeNames.XmlLiteralCDataSection)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralCDataSectionTypeDefinition;
#endregion
#region VB XML Literals - Comment
[Export]
[Name(ClassificationTypeNames.XmlLiteralComment)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralCommentTypeDefinition;
#endregion
#region VB XML Literals - Delimiter
[Export]
[Name(ClassificationTypeNames.XmlLiteralDelimiter)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralDelimiterTypeDefinition;
#endregion
#region VB XML Literals - Embedded Expression
[Export]
[Name(ClassificationTypeNames.XmlLiteralEmbeddedExpression)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralEmbeddedExpressionTypeDefinition;
#endregion
#region VB XML Literals - Entity Reference
[Export]
[Name(ClassificationTypeNames.XmlLiteralEntityReference)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralEntityReferenceTypeDefinition;
#endregion
#region VB XML Literals - Name
[Export]
[Name(ClassificationTypeNames.XmlLiteralName)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralNameTypeDefinition;
#endregion
#region VB XML Literals - Processing Instruction
[Export]
[Name(ClassificationTypeNames.XmlLiteralProcessingInstruction)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralProcessingInstructionTypeDefinition;
#endregion
#region VB XML Literals - Text
[Export]
[Name(ClassificationTypeNames.XmlLiteralText)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition XmlLiteralTextTypeDefinition;
#endregion
#region Reassigned Variable
[Export]
[Name(ClassificationTypeNames.ReassignedVariable)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition ReassignedVariableTypeDefinition;
#endregion
#region Static Symbol
[Export]
[Name(ClassificationTypeNames.StaticSymbol)]
[BaseDefinition(PredefinedClassificationTypeNames.FormalLanguage)]
internal readonly ClassificationTypeDefinition StaticSymbolTypeDefinition;
#endregion
#region Operator - Overloaded
// Operator - Overloaded sets its BaseDefinitions to be Operator so that
// in the absence of specific styling they will appear as operators.
[Export]
[Name(ClassificationTypeNames.OperatorOverloaded)]
[BaseDefinition(PredefinedClassificationTypeNames.Operator)]
internal readonly ClassificationTypeDefinition OperatorOverloadTypeDefinition;
#endregion
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/VisualBasic/Portable/Semantics/StatementSyntaxWalker.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' This class walks all the statements in some syntax, in order, except those statements that are contained
''' inside expressions (a statement can occur inside an expression if it is inside
''' a lambda.)
'''
''' This is used when collecting the declarations and declaration spaces of a method body.
'''
''' Typically the client overrides this class and overrides various Visit methods, being sure to always
''' delegate back to the base.
''' </summary>
Friend Class StatementSyntaxWalker
Inherits VisualBasicSyntaxVisitor
Public Overridable Sub VisitList(list As IEnumerable(Of VisualBasicSyntaxNode))
For Each n In list
Visit(n)
Next
End Sub
Public Overrides Sub VisitCompilationUnit(node As CompilationUnitSyntax)
VisitList(node.Options)
VisitList(node.Imports)
VisitList(node.Attributes)
VisitList(node.Members)
End Sub
Public Overrides Sub VisitNamespaceBlock(node As NamespaceBlockSyntax)
Visit(node.NamespaceStatement)
VisitList(node.Members)
Visit(node.EndNamespaceStatement)
End Sub
Public Overrides Sub VisitModuleBlock(ByVal node As ModuleBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitClassBlock(ByVal node As ClassBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Inherits)
VisitList(node.Implements)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitStructureBlock(ByVal node As StructureBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Inherits)
VisitList(node.Implements)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Inherits)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitEnumBlock(ByVal node As EnumBlockSyntax)
Visit(node.EnumStatement)
VisitList(node.Members)
Visit(node.EndEnumStatement)
End Sub
Public Overrides Sub VisitMethodBlock(ByVal node As MethodBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitConstructorBlock(node As ConstructorBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitOperatorBlock(node As OperatorBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitAccessorBlock(node As AccessorBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitPropertyBlock(ByVal node As PropertyBlockSyntax)
Visit(node.PropertyStatement)
VisitList(node.Accessors)
Visit(node.EndPropertyStatement)
End Sub
Public Overrides Sub VisitEventBlock(ByVal node As EventBlockSyntax)
Visit(node.EventStatement)
VisitList(node.Accessors)
Visit(node.EndEventStatement)
End Sub
Public Overrides Sub VisitWhileBlock(ByVal node As WhileBlockSyntax)
Visit(node.WhileStatement)
VisitList(node.Statements)
Visit(node.EndWhileStatement)
End Sub
Public Overrides Sub VisitUsingBlock(ByVal node As UsingBlockSyntax)
Visit(node.UsingStatement)
VisitList(node.Statements)
Visit(node.EndUsingStatement)
End Sub
Public Overrides Sub VisitSyncLockBlock(ByVal node As SyncLockBlockSyntax)
Visit(node.SyncLockStatement)
VisitList(node.Statements)
Visit(node.EndSyncLockStatement)
End Sub
Public Overrides Sub VisitWithBlock(ByVal node As WithBlockSyntax)
Visit(node.WithStatement)
VisitList(node.Statements)
Visit(node.EndWithStatement)
End Sub
Public Overrides Sub VisitSingleLineIfStatement(ByVal node As SingleLineIfStatementSyntax)
VisitList(node.Statements)
Visit(node.ElseClause)
End Sub
Public Overrides Sub VisitSingleLineElseClause(ByVal node As SingleLineElseClauseSyntax)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitMultiLineIfBlock(ByVal node As MultiLineIfBlockSyntax)
Visit(node.IfStatement)
VisitList(node.Statements)
VisitList(node.ElseIfBlocks)
Visit(node.ElseBlock)
Visit(node.EndIfStatement)
End Sub
Public Overrides Sub VisitElseIfBlock(ByVal node As ElseIfBlockSyntax)
Visit(node.ElseIfStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitElseBlock(ByVal node As ElseBlockSyntax)
Visit(node.ElseStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitTryBlock(ByVal node As TryBlockSyntax)
Visit(node.TryStatement)
VisitList(node.Statements)
VisitList(node.CatchBlocks)
Visit(node.FinallyBlock)
Visit(node.EndTryStatement)
End Sub
Public Overrides Sub VisitCatchBlock(ByVal node As CatchBlockSyntax)
Visit(node.CatchStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitFinallyBlock(ByVal node As FinallyBlockSyntax)
Visit(node.FinallyStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitSelectBlock(ByVal node As SelectBlockSyntax)
Visit(node.SelectStatement)
VisitList(node.CaseBlocks)
Visit(node.EndSelectStatement)
End Sub
Public Overrides Sub VisitCaseBlock(ByVal node As CaseBlockSyntax)
Visit(node.CaseStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitDoLoopBlock(ByVal node As DoLoopBlockSyntax)
Visit(node.DoStatement)
VisitList(node.Statements)
Visit(node.LoopStatement)
End Sub
Public Overrides Sub VisitForBlock(ByVal node As ForBlockSyntax)
Visit(node.ForStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitForEachBlock(ByVal node As ForEachBlockSyntax)
Visit(node.ForEachStatement)
VisitList(node.Statements)
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.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' This class walks all the statements in some syntax, in order, except those statements that are contained
''' inside expressions (a statement can occur inside an expression if it is inside
''' a lambda.)
'''
''' This is used when collecting the declarations and declaration spaces of a method body.
'''
''' Typically the client overrides this class and overrides various Visit methods, being sure to always
''' delegate back to the base.
''' </summary>
Friend Class StatementSyntaxWalker
Inherits VisualBasicSyntaxVisitor
Public Overridable Sub VisitList(list As IEnumerable(Of VisualBasicSyntaxNode))
For Each n In list
Visit(n)
Next
End Sub
Public Overrides Sub VisitCompilationUnit(node As CompilationUnitSyntax)
VisitList(node.Options)
VisitList(node.Imports)
VisitList(node.Attributes)
VisitList(node.Members)
End Sub
Public Overrides Sub VisitNamespaceBlock(node As NamespaceBlockSyntax)
Visit(node.NamespaceStatement)
VisitList(node.Members)
Visit(node.EndNamespaceStatement)
End Sub
Public Overrides Sub VisitModuleBlock(ByVal node As ModuleBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitClassBlock(ByVal node As ClassBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Inherits)
VisitList(node.Implements)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitStructureBlock(ByVal node As StructureBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Inherits)
VisitList(node.Implements)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitInterfaceBlock(ByVal node As InterfaceBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Inherits)
VisitList(node.Members)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitEnumBlock(ByVal node As EnumBlockSyntax)
Visit(node.EnumStatement)
VisitList(node.Members)
Visit(node.EndEnumStatement)
End Sub
Public Overrides Sub VisitMethodBlock(ByVal node As MethodBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitConstructorBlock(node As ConstructorBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitOperatorBlock(node As OperatorBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitAccessorBlock(node As AccessorBlockSyntax)
Visit(node.BlockStatement)
VisitList(node.Statements)
Visit(node.EndBlockStatement)
End Sub
Public Overrides Sub VisitPropertyBlock(ByVal node As PropertyBlockSyntax)
Visit(node.PropertyStatement)
VisitList(node.Accessors)
Visit(node.EndPropertyStatement)
End Sub
Public Overrides Sub VisitEventBlock(ByVal node As EventBlockSyntax)
Visit(node.EventStatement)
VisitList(node.Accessors)
Visit(node.EndEventStatement)
End Sub
Public Overrides Sub VisitWhileBlock(ByVal node As WhileBlockSyntax)
Visit(node.WhileStatement)
VisitList(node.Statements)
Visit(node.EndWhileStatement)
End Sub
Public Overrides Sub VisitUsingBlock(ByVal node As UsingBlockSyntax)
Visit(node.UsingStatement)
VisitList(node.Statements)
Visit(node.EndUsingStatement)
End Sub
Public Overrides Sub VisitSyncLockBlock(ByVal node As SyncLockBlockSyntax)
Visit(node.SyncLockStatement)
VisitList(node.Statements)
Visit(node.EndSyncLockStatement)
End Sub
Public Overrides Sub VisitWithBlock(ByVal node As WithBlockSyntax)
Visit(node.WithStatement)
VisitList(node.Statements)
Visit(node.EndWithStatement)
End Sub
Public Overrides Sub VisitSingleLineIfStatement(ByVal node As SingleLineIfStatementSyntax)
VisitList(node.Statements)
Visit(node.ElseClause)
End Sub
Public Overrides Sub VisitSingleLineElseClause(ByVal node As SingleLineElseClauseSyntax)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitMultiLineIfBlock(ByVal node As MultiLineIfBlockSyntax)
Visit(node.IfStatement)
VisitList(node.Statements)
VisitList(node.ElseIfBlocks)
Visit(node.ElseBlock)
Visit(node.EndIfStatement)
End Sub
Public Overrides Sub VisitElseIfBlock(ByVal node As ElseIfBlockSyntax)
Visit(node.ElseIfStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitElseBlock(ByVal node As ElseBlockSyntax)
Visit(node.ElseStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitTryBlock(ByVal node As TryBlockSyntax)
Visit(node.TryStatement)
VisitList(node.Statements)
VisitList(node.CatchBlocks)
Visit(node.FinallyBlock)
Visit(node.EndTryStatement)
End Sub
Public Overrides Sub VisitCatchBlock(ByVal node As CatchBlockSyntax)
Visit(node.CatchStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitFinallyBlock(ByVal node As FinallyBlockSyntax)
Visit(node.FinallyStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitSelectBlock(ByVal node As SelectBlockSyntax)
Visit(node.SelectStatement)
VisitList(node.CaseBlocks)
Visit(node.EndSelectStatement)
End Sub
Public Overrides Sub VisitCaseBlock(ByVal node As CaseBlockSyntax)
Visit(node.CaseStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitDoLoopBlock(ByVal node As DoLoopBlockSyntax)
Visit(node.DoStatement)
VisitList(node.Statements)
Visit(node.LoopStatement)
End Sub
Public Overrides Sub VisitForBlock(ByVal node As ForBlockSyntax)
Visit(node.ForStatement)
VisitList(node.Statements)
End Sub
Public Overrides Sub VisitForEachBlock(ByVal node As ForEachBlockSyntax)
Visit(node.ForEachStatement)
VisitList(node.Statements)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/CSharp/Portable/Lowering/LocalRewriter/LocalRewriter_Await.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
return VisitAwaitExpression(node, true);
}
public BoundExpression VisitAwaitExpression(BoundAwaitExpression node, bool used)
{
return RewriteAwaitExpression((BoundExpression)base.VisitAwaitExpression(node)!, used);
}
private BoundExpression RewriteAwaitExpression(SyntaxNode syntax, BoundExpression rewrittenExpression, BoundAwaitableInfo awaitableInfo, TypeSymbol type, bool used)
{
return RewriteAwaitExpression(new BoundAwaitExpression(syntax, rewrittenExpression, awaitableInfo, type) { WasCompilerGenerated = true }, used);
}
/// <summary>
/// Lower an await expression that has already had its components rewritten.
/// </summary>
private BoundExpression RewriteAwaitExpression(BoundExpression rewrittenAwait, bool used)
{
_sawAwait = true;
if (!used)
{
// Await expression is already at the statement level.
return rewrittenAwait;
}
// The await expression will be lowered to code that involves the use of side-effects
// such as jumps and labels, which we can only emit with an empty stack, so we require
// that the await expression itself is produced only when the stack is empty.
// Therefore it is represented by a BoundSpillSequence. The resulting nodes will be "spilled" to move
// such statements to the top level (i.e. into the enclosing statement list). Here we ensure
// that the await result itself is stored into a temp at the statement level, as that is
// the form handled by async lowering.
_needsSpilling = true;
var tempAccess = _factory.StoreToTemp(rewrittenAwait, out BoundAssignmentOperator tempAssignment, syntaxOpt: rewrittenAwait.Syntax,
kind: SynthesizedLocalKind.Spill);
return new BoundSpillSequence(
syntax: rewrittenAwait.Syntax,
locals: ImmutableArray.Create<LocalSymbol>(tempAccess.LocalSymbol),
sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment),
value: tempAccess,
type: tempAccess.Type);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.CSharp.Symbols;
namespace Microsoft.CodeAnalysis.CSharp
{
internal sealed partial class LocalRewriter
{
public override BoundNode VisitAwaitExpression(BoundAwaitExpression node)
{
return VisitAwaitExpression(node, true);
}
public BoundExpression VisitAwaitExpression(BoundAwaitExpression node, bool used)
{
return RewriteAwaitExpression((BoundExpression)base.VisitAwaitExpression(node)!, used);
}
private BoundExpression RewriteAwaitExpression(SyntaxNode syntax, BoundExpression rewrittenExpression, BoundAwaitableInfo awaitableInfo, TypeSymbol type, bool used)
{
return RewriteAwaitExpression(new BoundAwaitExpression(syntax, rewrittenExpression, awaitableInfo, type) { WasCompilerGenerated = true }, used);
}
/// <summary>
/// Lower an await expression that has already had its components rewritten.
/// </summary>
private BoundExpression RewriteAwaitExpression(BoundExpression rewrittenAwait, bool used)
{
_sawAwait = true;
if (!used)
{
// Await expression is already at the statement level.
return rewrittenAwait;
}
// The await expression will be lowered to code that involves the use of side-effects
// such as jumps and labels, which we can only emit with an empty stack, so we require
// that the await expression itself is produced only when the stack is empty.
// Therefore it is represented by a BoundSpillSequence. The resulting nodes will be "spilled" to move
// such statements to the top level (i.e. into the enclosing statement list). Here we ensure
// that the await result itself is stored into a temp at the statement level, as that is
// the form handled by async lowering.
_needsSpilling = true;
var tempAccess = _factory.StoreToTemp(rewrittenAwait, out BoundAssignmentOperator tempAssignment, syntaxOpt: rewrittenAwait.Syntax,
kind: SynthesizedLocalKind.Spill);
return new BoundSpillSequence(
syntax: rewrittenAwait.Syntax,
locals: ImmutableArray.Create<LocalSymbol>(tempAccess.LocalSymbol),
sideEffects: ImmutableArray.Create<BoundExpression>(tempAssignment),
value: tempAccess,
type: tempAccess.Type);
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/VisualBasic/Portable/Errors/ErrorMessageHelpers.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module ErrorMessageHelpers
<Extension()>
Public Function ToDisplay(access As Accessibility) As String
Select Case access
Case Accessibility.NotApplicable
Return ""
Case Accessibility.Private
Return "Private"
Case Accessibility.Protected
Return "Protected"
Case Accessibility.ProtectedOrFriend
Return "Protected Friend"
Case Accessibility.ProtectedAndFriend
Return "Private Protected"
Case Accessibility.Friend
Return "Friend"
Case Accessibility.Public
Return "Public"
Case Else
Throw ExceptionUtilities.UnexpectedValue(access)
End Select
End Function
End Module
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.CompilerServices
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Friend Module ErrorMessageHelpers
<Extension()>
Public Function ToDisplay(access As Accessibility) As String
Select Case access
Case Accessibility.NotApplicable
Return ""
Case Accessibility.Private
Return "Private"
Case Accessibility.Protected
Return "Protected"
Case Accessibility.ProtectedOrFriend
Return "Protected Friend"
Case Accessibility.ProtectedAndFriend
Return "Private Protected"
Case Accessibility.Friend
Return "Friend"
Case Accessibility.Public
Return "Public"
Case Else
Throw ExceptionUtilities.UnexpectedValue(access)
End Select
End Function
End Module
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/VisualStudio/Core/Def/Implementation/Progression/GraphNodeIdCreation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.CodeSchema;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Progression.CodeSchema;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
/// <summary>
/// A helper class that implements the creation of GraphNodeIds that matches the .dgml creation
/// by the metadata progression provider.
/// </summary>
internal static class GraphNodeIdCreation
{
public static GraphNodeId GetIdForDocument(Document document)
{
return
GraphNodeId.GetNested(
GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, new Uri(document.Project.FilePath, UriKind.RelativeOrAbsolute)),
GraphNodeId.GetPartial(CodeGraphNodeIdName.File, new Uri(document.FilePath, UriKind.RelativeOrAbsolute)));
}
internal static async Task<GraphNodeId> GetIdForNamespaceAsync(INamespaceSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var builder = new CodeQualifiedIdentifierBuilder();
var assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
builder.Assembly = assembly;
}
builder.Namespace = symbol.ToDisplayString();
return builder.ToQualifiedIdentifier();
}
internal static async Task<GraphNodeId> GetIdForTypeAsync(ITypeSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(symbol, true, solution, cancellationToken).ConfigureAwait(false);
var partials = nodes.ToArray();
if (partials.Length == 1)
{
return partials[0];
}
else
{
return GraphNodeId.GetNested(partials);
}
}
private static async Task<IEnumerable<GraphNodeId>> GetPartialsForNamespaceAndTypeAsync(ITypeSymbol symbol, bool includeNamespace, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
var items = new List<GraphNodeId>();
Uri assembly = null;
if (includeNamespace)
{
assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
}
var underlyingType = ChaseToUnderlyingType(symbol);
if (symbol.TypeKind == TypeKind.TypeParameter)
{
var typeParameter = (ITypeParameterSymbol)symbol;
if (typeParameter.TypeParameterKind == TypeParameterKind.Type)
{
if (includeNamespace && !typeParameter.ContainingNamespace.IsGlobalNamespace)
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, typeParameter.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol.ContainingType, CodeGraphNodeIdName.Type, solution, cancellationToken).ConfigureAwait(false));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, ((ITypeParameterSymbol)symbol).Ordinal.ToString()));
}
else
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, "System"));
}
else if (underlyingType.ContainingNamespace != null && !underlyingType.ContainingNamespace.IsGlobalNamespace)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, underlyingType.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol, CodeGraphNodeIdName.Type, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false));
}
return items;
}
private static async Task<GraphNodeId> GetPartialForTypeAsync(ITypeSymbol symbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
if (symbol is IArrayTypeSymbol arrayType)
{
return await GetPartialForArrayTypeAsync(arrayType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is INamedTypeSymbol namedType)
{
return await GetPartialForNamedTypeAsync(namedType, nodeName, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false);
}
else if (symbol is IPointerTypeSymbol pointerType)
{
return await GetPartialForPointerTypeAsync(pointerType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
return await GetPartialForTypeParameterSymbolAsync(typeParameter, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IDynamicTypeSymbol)
{
return GetPartialForDynamicType(nodeName);
}
throw ExceptionUtilities.Unreachable;
}
private static GraphNodeId GetPartialForDynamicType(GraphNodeIdName nodeName)
{
// We always consider this to be the "Object" type since Progression takes a very metadata-ish view of the type
return GraphNodeId.GetPartial(nodeName, "Object");
}
private static async Task<GraphNodeId> GetPartialForNamedTypeAsync(INamedTypeSymbol namedType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
// If this is a simple type, then we don't have much to do
if (namedType.ContainingType == null && Equals(namedType.ConstructedFrom, namedType) && namedType.Arity == 0)
{
return GraphNodeId.GetPartial(nodeName, namedType.Name);
}
else
{
// For a generic type, we need to populate "type" property with the following form:
//
// Type = (Name =...GenericParameterCount = GenericArguments =...ParentType =...)
//
// where "Name" contains a symbol name
// and "GenericParameterCount" contains the number of type parameters,
// and "GenericArguments" contains its type parameters' node information.
// and "ParentType" contains its containing type's node information.
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, namedType.Name));
if (namedType.Arity > 0)
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, namedType.Arity.ToString()));
}
// For the property "GenericArguments", we only populate them
// when type parameters are constructed using instance types (i.e., namedType.ConstructedFrom != namedType).
// However, there is a case where we need to populate "GenericArguments" even though arguments are not marked as "constructed"
// because a symbol is not marked as "constructed" when a type is constructed using its own type parameters.
// To distinguish this case, we use "isInGenericArguments" flag which we pass either to populate arguments recursively or to populate "ParentType".
var hasGenericArguments = (!Equals(namedType.ConstructedFrom, namedType) || isInGenericArguments) && namedType.TypeArguments != null && namedType.TypeArguments.Any();
if (hasGenericArguments)
{
var genericArguments = new List<GraphNodeId>();
foreach (var arg in namedType.TypeArguments)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(arg, includeNamespace: true, solution: solution, cancellationToken: cancellationToken, isInGenericArguments: true).ConfigureAwait(false);
genericArguments.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
partials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.GenericArgumentsIdentifier,
genericArguments.ToArray()));
}
if (namedType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(namedType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken, hasGenericArguments).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
}
private static async Task<GraphNodeId> GetPartialForPointerTypeAsync(IPointerTypeSymbol pointerType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var indirection = 1;
while (pointerType.PointedAtType.TypeKind == TypeKind.Pointer)
{
indirection++;
pointerType = (IPointerTypeSymbol)pointerType.PointedAtType;
}
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, pointerType.PointedAtType.Name));
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Indirection, indirection.ToString()));
if (pointerType.PointedAtType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(pointerType.PointedAtType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForArrayTypeAsync(IArrayTypeSymbol arrayType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
var underlyingType = ChaseToUnderlyingType(arrayType);
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, "Object"));
}
else if (underlyingType.TypeKind != TypeKind.TypeParameter)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, underlyingType.Name));
}
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.ArrayRank, arrayType.Rank.ToString()));
partials.Add(await GetPartialForTypeAsync(arrayType.ElementType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForTypeParameterSymbolAsync(ITypeParameterSymbol typeParameterSymbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
if (typeParameterSymbol.TypeParameterKind == TypeParameterKind.Method)
{
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false,
GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, typeParameterSymbol.Ordinal.ToString())));
}
else
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(typeParameterSymbol, false, solution, cancellationToken).ConfigureAwait(false);
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false, nodes.ToArray()));
}
}
private static ITypeSymbol ChaseToUnderlyingType(ITypeSymbol symbol)
{
while (symbol.TypeKind == TypeKind.Array)
{
symbol = ((IArrayTypeSymbol)symbol).ElementType;
}
while (symbol.TypeKind == TypeKind.Pointer)
{
symbol = ((IPointerTypeSymbol)symbol).PointedAtType;
}
return symbol;
}
public static async Task<GraphNodeId> GetIdForMemberAsync(ISymbol member, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
partials.AddRange(await GetPartialsForNamespaceAndTypeAsync(member.ContainingType, true, solution, cancellationToken).ConfigureAwait(false));
var parameters = member.GetParameters();
if (parameters.Any() || member.GetArity() > 0)
{
var memberPartials = new List<GraphNodeId>();
memberPartials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, member.MetadataName));
if (member.GetArity() > 0)
{
memberPartials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, member.GetArity().ToString()));
}
if (parameters.Any())
{
var parameterTypeIds = new List<GraphNodeId>();
foreach (var p in parameters)
{
var parameterIds = await GetPartialsForNamespaceAndTypeAsync(p.Type, true, solution, cancellationToken).ConfigureAwait(false);
var nodes = parameterIds.ToList();
if (p.IsRefOrOut())
{
nodes.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, ParamKind.Ref));
}
parameterTypeIds.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
if (member is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.Conversion)
{
// For explicit/implicit conversion operators, we need to include the return type in the method Id,
// because there can be several conversion operators with same parameters and only differ by return type.
// For example,
//
// public class Class1
// {
// public static explicit (explicit) operator int(Class1 c) { ... }
// public static explicit (explicit) operator double(Class1 c) { ... }
// }
var nodes = await GetPartialsForNamespaceAndTypeAsync(methodSymbol.ReturnType, true, solution, cancellationToken).ConfigureAwait(false);
var returnTypePartial = nodes.ToList();
returnTypePartial.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, Microsoft.VisualStudio.GraphModel.CodeSchema.ParamKind.Return));
var returnCollection = GraphNodeId.GetNested(returnTypePartial.ToArray());
parameterTypeIds.Add(returnCollection);
}
memberPartials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.OverloadingParameters,
parameterTypeIds.ToArray()));
}
partials.Add(GraphNodeId.GetPartial(
CodeGraphNodeIdName.Member,
MakeCollectionIfNecessary(memberPartials.ToArray())));
}
else
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Member, member.MetadataName));
}
return GraphNodeId.GetNested(partials.ToArray());
}
private static object MakeCollectionIfNecessary(GraphNodeId[] array)
{
// Place the array of GraphNodeId's into the collection if necessary, so to make them appear in VS Properties Panel
if (array.Length > 1)
{
return new GraphNodeIdCollection(false, array);
}
return GraphNodeId.GetNested(array);
}
private static IAssemblySymbol GetContainingAssembly(ISymbol symbol)
{
if (symbol.ContainingAssembly != null)
{
return symbol.ContainingAssembly;
}
if (!(symbol is ITypeSymbol typeSymbol))
{
return null;
}
var underlyingType = ChaseToUnderlyingType(typeSymbol);
if (Equals(typeSymbol, underlyingType))
{
// when symbol is for dynamic type
return null;
}
return GetContainingAssembly(underlyingType);
}
private static async Task<Uri> GetAssemblyFullPathAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var containingAssembly = GetContainingAssembly(symbol);
return await GetAssemblyFullPathAsync(containingAssembly, solution, cancellationToken).ConfigureAwait(false);
}
private static async Task<Uri> GetAssemblyFullPathAsync(IAssemblySymbol containingAssembly, Solution solution, CancellationToken cancellationToken)
{
if (containingAssembly == null)
{
return null;
}
var foundProject = solution.GetProject(containingAssembly, cancellationToken);
if (foundProject != null)
{
if (solution.Workspace is VisualStudioWorkspace)
{
// TODO: audit the OutputFilePath and whether this is bin or obj
if (!string.IsNullOrWhiteSpace(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.RelativeOrAbsolute);
}
return null;
}
}
else
{
// This symbol is not present in the source code, we need to resolve it from the references!
// If a MetadataReference returned by Compilation.GetMetadataReference(AssemblySymbol) has a path, we could use it.
foreach (var project in solution.Projects)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
if (compilation != null)
{
if (compilation.GetMetadataReference(containingAssembly) is PortableExecutableReference reference && !string.IsNullOrEmpty(reference.FilePath))
{
return new Uri(reference.FilePath, UriKind.RelativeOrAbsolute);
}
}
}
}
// If we are not in VS, return project.OutputFilePath as a reasonable fallback.
// For an example, it could be AdhocWorkspace for unit tests.
if (foundProject != null && !string.IsNullOrEmpty(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.Absolute);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForAssemblyAsync(IAssemblySymbol assemblySymbol, Solution solution, CancellationToken cancellationToken)
{
var assembly = await GetAssemblyFullPathAsync(assemblySymbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
var builder = new CodeQualifiedIdentifierBuilder();
builder.Assembly = assembly;
return builder.ToQualifiedIdentifier();
}
return null;
}
internal static async Task<GraphNodeId> GetIdForParameterAsync(IParameterSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support parameters inside methods or properties.
throw new ArgumentException("symbol");
}
var containingSymbol = symbol.ContainingSymbol;
if (containingSymbol is IMethodSymbol method && method.AssociatedSymbol != null && method.AssociatedSymbol.Kind == SymbolKind.Property)
{
var property = (IPropertySymbol)method.AssociatedSymbol;
if (property.Parameters.Any(p => p.Name == symbol.Name))
{
containingSymbol = property;
}
}
var memberId = await GetIdForMemberAsync(containingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
return memberId + GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, symbol.Name);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForLocalVariableAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support local variables inside methods or properties.
throw new ArgumentException("symbol");
}
var memberId = await GetIdForMemberAsync(symbol.ContainingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
var builder = new CodeQualifiedIdentifierBuilder(memberId);
builder.LocalVariable = symbol.Name;
builder.LocalVariableIndex = await GetLocalVariableIndexAsync(symbol, solution, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
return builder.ToQualifiedIdentifier();
}
return null;
}
/// <summary>
/// Get the position of where a given local variable is defined considering there could be multiple variables with the same name in method body.
/// For example, in "int M() { { int goo = 0; ...} { int goo = 1; ...} }",
/// the return value for the first "goo" would be 0 while the value for the second one would be 1.
/// It will be used to create a node with LocalVariableIndex for a non-zero value.
/// In the above example, hence, a node id for the first "goo" would look like (... Member=M LocalVariable=bar)
/// but an id for the second "goo" would be (... Member=M LocalVariable=bar LocalVariableIndex=1)
/// </summary>
private static async Task<int> GetLocalVariableIndexAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var pos = 0;
foreach (var reference in symbol.ContainingSymbol.DeclaringSyntaxReferences)
{
var currentNode = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
// For VB, we have to ask its parent to get local variables within this method body
// since DeclaringSyntaxReferences return statement rather than enclosing block.
if (currentNode != null && symbol.Language == LanguageNames.VisualBasic)
{
currentNode = currentNode.Parent;
}
if (currentNode != null)
{
var document = solution.GetDocument(currentNode.SyntaxTree);
if (document == null)
{
continue;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var node in currentNode.DescendantNodes())
{
var current = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (current != null && current.Name == symbol.Name && (current.Kind == SymbolKind.Local || current.Kind == SymbolKind.RangeVariable))
{
if (!current.Equals(symbol))
{
pos++;
}
else
{
return pos;
}
}
}
}
}
throw ExceptionUtilities.Unreachable;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.VisualStudio.GraphModel;
using Microsoft.VisualStudio.GraphModel.CodeSchema;
using Microsoft.VisualStudio.GraphModel.Schemas;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Progression.CodeSchema;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression
{
/// <summary>
/// A helper class that implements the creation of GraphNodeIds that matches the .dgml creation
/// by the metadata progression provider.
/// </summary>
internal static class GraphNodeIdCreation
{
public static GraphNodeId GetIdForDocument(Document document)
{
return
GraphNodeId.GetNested(
GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, new Uri(document.Project.FilePath, UriKind.RelativeOrAbsolute)),
GraphNodeId.GetPartial(CodeGraphNodeIdName.File, new Uri(document.FilePath, UriKind.RelativeOrAbsolute)));
}
internal static async Task<GraphNodeId> GetIdForNamespaceAsync(INamespaceSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var builder = new CodeQualifiedIdentifierBuilder();
var assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
builder.Assembly = assembly;
}
builder.Namespace = symbol.ToDisplayString();
return builder.ToQualifiedIdentifier();
}
internal static async Task<GraphNodeId> GetIdForTypeAsync(ITypeSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(symbol, true, solution, cancellationToken).ConfigureAwait(false);
var partials = nodes.ToArray();
if (partials.Length == 1)
{
return partials[0];
}
else
{
return GraphNodeId.GetNested(partials);
}
}
private static async Task<IEnumerable<GraphNodeId>> GetPartialsForNamespaceAndTypeAsync(ITypeSymbol symbol, bool includeNamespace, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
var items = new List<GraphNodeId>();
Uri assembly = null;
if (includeNamespace)
{
assembly = await GetAssemblyFullPathAsync(symbol, solution, cancellationToken).ConfigureAwait(false);
}
var underlyingType = ChaseToUnderlyingType(symbol);
if (symbol.TypeKind == TypeKind.TypeParameter)
{
var typeParameter = (ITypeParameterSymbol)symbol;
if (typeParameter.TypeParameterKind == TypeParameterKind.Type)
{
if (includeNamespace && !typeParameter.ContainingNamespace.IsGlobalNamespace)
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, typeParameter.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol.ContainingType, CodeGraphNodeIdName.Type, solution, cancellationToken).ConfigureAwait(false));
}
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, ((ITypeParameterSymbol)symbol).Ordinal.ToString()));
}
else
{
if (assembly != null)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Assembly, assembly));
}
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, "System"));
}
else if (underlyingType.ContainingNamespace != null && !underlyingType.ContainingNamespace.IsGlobalNamespace)
{
items.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Namespace, underlyingType.ContainingNamespace.ToDisplayString()));
}
items.Add(await GetPartialForTypeAsync(symbol, CodeGraphNodeIdName.Type, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false));
}
return items;
}
private static async Task<GraphNodeId> GetPartialForTypeAsync(ITypeSymbol symbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
if (symbol is IArrayTypeSymbol arrayType)
{
return await GetPartialForArrayTypeAsync(arrayType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is INamedTypeSymbol namedType)
{
return await GetPartialForNamedTypeAsync(namedType, nodeName, solution, cancellationToken, isInGenericArguments).ConfigureAwait(false);
}
else if (symbol is IPointerTypeSymbol pointerType)
{
return await GetPartialForPointerTypeAsync(pointerType, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is ITypeParameterSymbol typeParameter)
{
return await GetPartialForTypeParameterSymbolAsync(typeParameter, nodeName, solution, cancellationToken).ConfigureAwait(false);
}
else if (symbol is IDynamicTypeSymbol)
{
return GetPartialForDynamicType(nodeName);
}
throw ExceptionUtilities.Unreachable;
}
private static GraphNodeId GetPartialForDynamicType(GraphNodeIdName nodeName)
{
// We always consider this to be the "Object" type since Progression takes a very metadata-ish view of the type
return GraphNodeId.GetPartial(nodeName, "Object");
}
private static async Task<GraphNodeId> GetPartialForNamedTypeAsync(INamedTypeSymbol namedType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken, bool isInGenericArguments = false)
{
// If this is a simple type, then we don't have much to do
if (namedType.ContainingType == null && Equals(namedType.ConstructedFrom, namedType) && namedType.Arity == 0)
{
return GraphNodeId.GetPartial(nodeName, namedType.Name);
}
else
{
// For a generic type, we need to populate "type" property with the following form:
//
// Type = (Name =...GenericParameterCount = GenericArguments =...ParentType =...)
//
// where "Name" contains a symbol name
// and "GenericParameterCount" contains the number of type parameters,
// and "GenericArguments" contains its type parameters' node information.
// and "ParentType" contains its containing type's node information.
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, namedType.Name));
if (namedType.Arity > 0)
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, namedType.Arity.ToString()));
}
// For the property "GenericArguments", we only populate them
// when type parameters are constructed using instance types (i.e., namedType.ConstructedFrom != namedType).
// However, there is a case where we need to populate "GenericArguments" even though arguments are not marked as "constructed"
// because a symbol is not marked as "constructed" when a type is constructed using its own type parameters.
// To distinguish this case, we use "isInGenericArguments" flag which we pass either to populate arguments recursively or to populate "ParentType".
var hasGenericArguments = (!Equals(namedType.ConstructedFrom, namedType) || isInGenericArguments) && namedType.TypeArguments != null && namedType.TypeArguments.Any();
if (hasGenericArguments)
{
var genericArguments = new List<GraphNodeId>();
foreach (var arg in namedType.TypeArguments)
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(arg, includeNamespace: true, solution: solution, cancellationToken: cancellationToken, isInGenericArguments: true).ConfigureAwait(false);
genericArguments.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
partials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.GenericArgumentsIdentifier,
genericArguments.ToArray()));
}
if (namedType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(namedType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken, hasGenericArguments).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
}
private static async Task<GraphNodeId> GetPartialForPointerTypeAsync(IPointerTypeSymbol pointerType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var indirection = 1;
while (pointerType.PointedAtType.TypeKind == TypeKind.Pointer)
{
indirection++;
pointerType = (IPointerTypeSymbol)pointerType.PointedAtType;
}
var partials = new List<GraphNodeId>();
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, pointerType.PointedAtType.Name));
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Indirection, indirection.ToString()));
if (pointerType.PointedAtType.ContainingType != null)
{
partials.Add(await GetPartialForTypeAsync(pointerType.PointedAtType.ContainingType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
}
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForArrayTypeAsync(IArrayTypeSymbol arrayType, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
var underlyingType = ChaseToUnderlyingType(arrayType);
if (underlyingType.TypeKind == TypeKind.Dynamic)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, "Object"));
}
else if (underlyingType.TypeKind != TypeKind.TypeParameter)
{
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, underlyingType.Name));
}
partials.Add(GraphNodeId.GetPartial(CodeQualifiedName.ArrayRank, arrayType.Rank.ToString()));
partials.Add(await GetPartialForTypeAsync(arrayType.ElementType, CodeGraphNodeIdName.ParentType, solution, cancellationToken).ConfigureAwait(false));
return GraphNodeId.GetPartial(nodeName, MakeCollectionIfNecessary(partials.ToArray()));
}
private static async Task<GraphNodeId> GetPartialForTypeParameterSymbolAsync(ITypeParameterSymbol typeParameterSymbol, GraphNodeIdName nodeName, Solution solution, CancellationToken cancellationToken)
{
if (typeParameterSymbol.TypeParameterKind == TypeParameterKind.Method)
{
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false,
GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, typeParameterSymbol.Ordinal.ToString())));
}
else
{
var nodes = await GetPartialsForNamespaceAndTypeAsync(typeParameterSymbol, false, solution, cancellationToken).ConfigureAwait(false);
return GraphNodeId.GetPartial(nodeName,
new GraphNodeIdCollection(false, nodes.ToArray()));
}
}
private static ITypeSymbol ChaseToUnderlyingType(ITypeSymbol symbol)
{
while (symbol.TypeKind == TypeKind.Array)
{
symbol = ((IArrayTypeSymbol)symbol).ElementType;
}
while (symbol.TypeKind == TypeKind.Pointer)
{
symbol = ((IPointerTypeSymbol)symbol).PointedAtType;
}
return symbol;
}
public static async Task<GraphNodeId> GetIdForMemberAsync(ISymbol member, Solution solution, CancellationToken cancellationToken)
{
var partials = new List<GraphNodeId>();
partials.AddRange(await GetPartialsForNamespaceAndTypeAsync(member.ContainingType, true, solution, cancellationToken).ConfigureAwait(false));
var parameters = member.GetParameters();
if (parameters.Any() || member.GetArity() > 0)
{
var memberPartials = new List<GraphNodeId>();
memberPartials.Add(GraphNodeId.GetPartial(CodeQualifiedName.Name, member.MetadataName));
if (member.GetArity() > 0)
{
memberPartials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.GenericParameterCountIdentifier, member.GetArity().ToString()));
}
if (parameters.Any())
{
var parameterTypeIds = new List<GraphNodeId>();
foreach (var p in parameters)
{
var parameterIds = await GetPartialsForNamespaceAndTypeAsync(p.Type, true, solution, cancellationToken).ConfigureAwait(false);
var nodes = parameterIds.ToList();
if (p.IsRefOrOut())
{
nodes.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, ParamKind.Ref));
}
parameterTypeIds.Add(GraphNodeId.GetNested(nodes.ToArray()));
}
if (member is IMethodSymbol methodSymbol && methodSymbol.MethodKind == MethodKind.Conversion)
{
// For explicit/implicit conversion operators, we need to include the return type in the method Id,
// because there can be several conversion operators with same parameters and only differ by return type.
// For example,
//
// public class Class1
// {
// public static explicit (explicit) operator int(Class1 c) { ... }
// public static explicit (explicit) operator double(Class1 c) { ... }
// }
var nodes = await GetPartialsForNamespaceAndTypeAsync(methodSymbol.ReturnType, true, solution, cancellationToken).ConfigureAwait(false);
var returnTypePartial = nodes.ToList();
returnTypePartial.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.ParamKind, Microsoft.VisualStudio.GraphModel.CodeSchema.ParamKind.Return));
var returnCollection = GraphNodeId.GetNested(returnTypePartial.ToArray());
parameterTypeIds.Add(returnCollection);
}
memberPartials.Add(GraphNodeId.GetArray(
CodeGraphNodeIdName.OverloadingParameters,
parameterTypeIds.ToArray()));
}
partials.Add(GraphNodeId.GetPartial(
CodeGraphNodeIdName.Member,
MakeCollectionIfNecessary(memberPartials.ToArray())));
}
else
{
partials.Add(GraphNodeId.GetPartial(CodeGraphNodeIdName.Member, member.MetadataName));
}
return GraphNodeId.GetNested(partials.ToArray());
}
private static object MakeCollectionIfNecessary(GraphNodeId[] array)
{
// Place the array of GraphNodeId's into the collection if necessary, so to make them appear in VS Properties Panel
if (array.Length > 1)
{
return new GraphNodeIdCollection(false, array);
}
return GraphNodeId.GetNested(array);
}
private static IAssemblySymbol GetContainingAssembly(ISymbol symbol)
{
if (symbol.ContainingAssembly != null)
{
return symbol.ContainingAssembly;
}
if (!(symbol is ITypeSymbol typeSymbol))
{
return null;
}
var underlyingType = ChaseToUnderlyingType(typeSymbol);
if (Equals(typeSymbol, underlyingType))
{
// when symbol is for dynamic type
return null;
}
return GetContainingAssembly(underlyingType);
}
private static async Task<Uri> GetAssemblyFullPathAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var containingAssembly = GetContainingAssembly(symbol);
return await GetAssemblyFullPathAsync(containingAssembly, solution, cancellationToken).ConfigureAwait(false);
}
private static async Task<Uri> GetAssemblyFullPathAsync(IAssemblySymbol containingAssembly, Solution solution, CancellationToken cancellationToken)
{
if (containingAssembly == null)
{
return null;
}
var foundProject = solution.GetProject(containingAssembly, cancellationToken);
if (foundProject != null)
{
if (solution.Workspace is VisualStudioWorkspace)
{
// TODO: audit the OutputFilePath and whether this is bin or obj
if (!string.IsNullOrWhiteSpace(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.RelativeOrAbsolute);
}
return null;
}
}
else
{
// This symbol is not present in the source code, we need to resolve it from the references!
// If a MetadataReference returned by Compilation.GetMetadataReference(AssemblySymbol) has a path, we could use it.
foreach (var project in solution.Projects)
{
var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);
if (compilation != null)
{
if (compilation.GetMetadataReference(containingAssembly) is PortableExecutableReference reference && !string.IsNullOrEmpty(reference.FilePath))
{
return new Uri(reference.FilePath, UriKind.RelativeOrAbsolute);
}
}
}
}
// If we are not in VS, return project.OutputFilePath as a reasonable fallback.
// For an example, it could be AdhocWorkspace for unit tests.
if (foundProject != null && !string.IsNullOrEmpty(foundProject.OutputFilePath))
{
return new Uri(foundProject.OutputFilePath, UriKind.Absolute);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForAssemblyAsync(IAssemblySymbol assemblySymbol, Solution solution, CancellationToken cancellationToken)
{
var assembly = await GetAssemblyFullPathAsync(assemblySymbol, solution, cancellationToken).ConfigureAwait(false);
if (assembly != null)
{
var builder = new CodeQualifiedIdentifierBuilder();
builder.Assembly = assembly;
return builder.ToQualifiedIdentifier();
}
return null;
}
internal static async Task<GraphNodeId> GetIdForParameterAsync(IParameterSymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support parameters inside methods or properties.
throw new ArgumentException("symbol");
}
var containingSymbol = symbol.ContainingSymbol;
if (containingSymbol is IMethodSymbol method && method.AssociatedSymbol != null && method.AssociatedSymbol.Kind == SymbolKind.Property)
{
var property = (IPropertySymbol)method.AssociatedSymbol;
if (property.Parameters.Any(p => p.Name == symbol.Name))
{
containingSymbol = property;
}
}
var memberId = await GetIdForMemberAsync(containingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
return memberId + GraphNodeId.GetPartial(CodeGraphNodeIdName.Parameter, symbol.Name);
}
return null;
}
internal static async Task<GraphNodeId> GetIdForLocalVariableAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
if (symbol.ContainingSymbol == null ||
(symbol.ContainingSymbol.Kind != SymbolKind.Method && symbol.ContainingSymbol.Kind != SymbolKind.Property))
{
// We are only support local variables inside methods or properties.
throw new ArgumentException("symbol");
}
var memberId = await GetIdForMemberAsync(symbol.ContainingSymbol, solution, cancellationToken).ConfigureAwait(false);
if (memberId != null)
{
var builder = new CodeQualifiedIdentifierBuilder(memberId);
builder.LocalVariable = symbol.Name;
builder.LocalVariableIndex = await GetLocalVariableIndexAsync(symbol, solution, cancellationToken).ConfigureAwait(continueOnCapturedContext: false);
return builder.ToQualifiedIdentifier();
}
return null;
}
/// <summary>
/// Get the position of where a given local variable is defined considering there could be multiple variables with the same name in method body.
/// For example, in "int M() { { int goo = 0; ...} { int goo = 1; ...} }",
/// the return value for the first "goo" would be 0 while the value for the second one would be 1.
/// It will be used to create a node with LocalVariableIndex for a non-zero value.
/// In the above example, hence, a node id for the first "goo" would look like (... Member=M LocalVariable=bar)
/// but an id for the second "goo" would be (... Member=M LocalVariable=bar LocalVariableIndex=1)
/// </summary>
private static async Task<int> GetLocalVariableIndexAsync(ISymbol symbol, Solution solution, CancellationToken cancellationToken)
{
var pos = 0;
foreach (var reference in symbol.ContainingSymbol.DeclaringSyntaxReferences)
{
var currentNode = await reference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
// For VB, we have to ask its parent to get local variables within this method body
// since DeclaringSyntaxReferences return statement rather than enclosing block.
if (currentNode != null && symbol.Language == LanguageNames.VisualBasic)
{
currentNode = currentNode.Parent;
}
if (currentNode != null)
{
var document = solution.GetDocument(currentNode.SyntaxTree);
if (document == null)
{
continue;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var node in currentNode.DescendantNodes())
{
var current = semanticModel.GetDeclaredSymbol(node, cancellationToken);
if (current != null && current.Name == symbol.Name && (current.Kind == SymbolKind.Local || current.Kind == SymbolKind.RangeVariable))
{
if (!current.Equals(symbol))
{
pos++;
}
else
{
return pos;
}
}
}
}
}
throw ExceptionUtilities.Unreachable;
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/CSharp/Test/Emit/PDB/CSharpDeterministicBuildCompilationTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.PDB;
using Roslyn.Utilities;
using TestResources.NetFX;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class CSharpDeterministicBuildCompilationTests : CSharpTestBase, IEnumerable<object[]>
{
private static void VerifyCompilationOptions(
CSharpCompilationOptions originalOptions,
Compilation compilation,
EmitOptions emitOptions,
BlobReader compilationOptionsBlobReader,
string langVersion,
int sourceFileCount)
{
var pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader);
DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions);
// See CSharpCompilation.SerializeForPdb to see options that are included
pdbOptions.VerifyPdbOption("nullable", originalOptions.NullableContextOptions);
pdbOptions.VerifyPdbOption("checked", originalOptions.CheckOverflow);
pdbOptions.VerifyPdbOption("unsafe", originalOptions.AllowUnsafe);
Assert.Equal(langVersion, pdbOptions["language-version"]);
Assert.Equal(sourceFileCount.ToString(), pdbOptions["source-file-count"]);
var firstSyntaxTree = (CSharpSyntaxTree)compilation.SyntaxTrees.FirstOrDefault();
pdbOptions.VerifyPdbOption("define", firstSyntaxTree.Options.PreprocessorSymbolNames, isDefault: v => v.IsEmpty(), toString: v => string.Join(",", v));
}
private static void TestDeterministicCompilationCSharp(
string langVersion,
SyntaxTree[] syntaxTrees,
CSharpCompilationOptions compilationOptions,
EmitOptions emitOptions,
TestMetadataReferenceInfo[] metadataReferences,
int? debugDocumentsCount = null)
{
var targetFramework = TargetFramework.NetCoreApp;
var originalCompilation = CreateCompilation(
syntaxTrees,
references: metadataReferences.SelectAsArray(r => r.MetadataReference),
options: compilationOptions,
targetFramework: targetFramework);
var peBlob = originalCompilation.EmitToArray(options: emitOptions);
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var reproducible = entries[2];
var embedded = entries[3];
using (var embeddedPdb = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var pdbReader = embeddedPdb.GetMetadataReader();
var metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader);
var compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader);
Assert.Equal(debugDocumentsCount ?? syntaxTrees.Length, pdbReader.Documents.Count);
VerifyCompilationOptions(compilationOptions, originalCompilation, emitOptions, compilationOptionsReader, langVersion, syntaxTrees.Length);
DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, targetFramework, metadataReferenceReader);
}
}
}
[Theory]
[ClassData(typeof(CSharpDeterministicBuildCompilationTests))]
public void PortablePdb_DeterministicCompilation(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
{
var sourceOne = Parse(@"
using System;
class MainType
{
public static void Main()
{
Console.WriteLine();
}
}
", filename: "a.cs", options: parseOptions, encoding: Encoding.UTF8);
var sourceTwo = Parse(@"
class TypeTwo
{
}", filename: "b.cs", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var sourceThree = Parse(@"
class TypeThree
{
}", filename: "c.cs", options: parseOptions, encoding: Encoding.Unicode);
var referenceOneCompilation = CreateCompilation(
@"public struct StructWithReference
{
string PrivateData;
}
public struct StructWithValue
{
int PrivateData;
}", options: TestOptions.DebugDll);
var referenceTwoCompilation = CreateCompilation(
@"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);
using var referenceOne = TestMetadataReferenceInfo.Create(
referenceOneCompilation,
fullPath: "abcd.dll",
emitOptions: emitOptions);
using var referenceTwo = TestMetadataReferenceInfo.Create(
referenceTwoCompilation,
fullPath: "efgh.dll",
emitOptions: emitOptions);
var testSource = new[] { sourceOne, sourceTwo, sourceThree };
TestDeterministicCompilationCSharp(
parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(),
testSource,
compilationOptions,
emitOptions,
new[] { referenceOne, referenceTwo });
}
[Theory]
[ClassData(typeof(CSharpDeterministicBuildCompilationTests))]
public void PortablePdb_DeterministicCompilation_DuplicateFilePaths(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
{
var sourceOne = Parse(@"
using System;
class MainType
{
public static void Main()
{
Console.WriteLine();
}
}
", filename: "a.cs", options: parseOptions, encoding: Encoding.UTF8);
var sourceTwo = Parse(@"
class TypeTwo
{
}", filename: "b.cs", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var sourceThree = Parse(@"
class TypeThree
{
}", filename: "a.cs", options: parseOptions, encoding: Encoding.Unicode);
var referenceOneCompilation = CreateCompilation(
@"public struct StructWithReference
{
string PrivateData;
}
public struct StructWithValue
{
int PrivateData;
}", options: TestOptions.DebugDll);
var referenceTwoCompilation = CreateCompilation(
@"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);
using var referenceOne = TestMetadataReferenceInfo.Create(
referenceOneCompilation,
fullPath: "abcd.dll",
emitOptions: emitOptions);
using var referenceTwo = TestMetadataReferenceInfo.Create(
referenceTwoCompilation,
fullPath: "efgh.dll",
emitOptions: emitOptions);
var testSource = new[] { sourceOne, sourceTwo, sourceThree };
// Note that only one debug document can be present for each distinct source path.
// So if more than one syntax tree has the same file path, it won't be possible to do a rebuild from the DLL+PDB.
TestDeterministicCompilationCSharp(
parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(),
testSource,
compilationOptions,
emitOptions,
new[] { referenceOne, referenceTwo },
debugDocumentsCount: 2);
}
[ConditionalTheory(typeof(DesktopOnly))]
[ClassData(typeof(CSharpDeterministicBuildCompilationTests))]
public void PortablePdb_DeterministicCompilationWithSJIS(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
{
var sourceOne = Parse(@"
using System;
class MainType
{
public static void Main()
{
Console.WriteLine();
}
}
", filename: "a.cs", options: parseOptions, encoding: Encoding.UTF8);
var sourceTwo = Parse(@"
class TypeTwo
{
}", filename: "b.cs", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var sourceThree = Parse(@"
class TypeThree
{
}", filename: "c.cs", options: parseOptions, encoding: Encoding.GetEncoding(932)); // SJIS encoding
var referenceOneCompilation = CreateCompilation(
@"public struct StructWithReference
{
string PrivateData;
}
public struct StructWithValue
{
int PrivateData;
}", options: TestOptions.DebugDll);
var referenceTwoCompilation = CreateCompilation(
@"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);
using var referenceOne = TestMetadataReferenceInfo.Create(
referenceOneCompilation,
fullPath: "abcd.dll",
emitOptions: emitOptions);
using var referenceTwo = TestMetadataReferenceInfo.Create(
referenceTwoCompilation,
fullPath: "efgh.dll",
emitOptions: emitOptions);
var testSource = new[] { sourceOne, sourceTwo, sourceThree };
TestDeterministicCompilationCSharp(
parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(),
testSource,
compilationOptions,
emitOptions,
new[] { referenceOne, referenceTwo });
}
public IEnumerator<object[]> GetEnumerator() => GetTestParameters().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private static IEnumerable<object[]> GetTestParameters()
{
foreach (var compilationOptions in GetCompilationOptions())
{
foreach (var emitOptions in DeterministicBuildCompilationTestHelpers.GetEmitOptions())
{
foreach (var parseOptions in GetCSharpParseOptions())
{
yield return new object[] { compilationOptions, emitOptions, parseOptions };
}
}
}
}
private static IEnumerable<CSharpCompilationOptions> GetCompilationOptions()
{
// Provide non default options for to test that they are being serialized
// to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise
// everything should be non-default if possible. Diagnostic settings are ignored
// because they won't be serialized.
// Use constructor that requires all arguments. If new arguments are added, it's possible they need to be
// included in the pdb serialization and added to tests here
var defaultOptions = new CSharpCompilationOptions(
OutputKind.ConsoleApplication,
reportSuppressedDiagnostics: false,
moduleName: "Module",
mainTypeName: "MainType",
scriptClassName: null,
usings: new[] { "System", "System.Threading" },
optimizationLevel: OptimizationLevel.Debug,
checkOverflow: true,
allowUnsafe: true,
cryptoKeyContainer: null,
cryptoKeyFile: null,
cryptoPublicKey: default,
delaySign: null,
platform: Platform.AnyCpu,
generalDiagnosticOption: ReportDiagnostic.Default,
warningLevel: 4,
specificDiagnosticOptions: null,
concurrentBuild: true,
deterministic: true,
currentLocalTime: default,
debugPlusMode: false,
xmlReferenceResolver: null,
sourceReferenceResolver: null,
syntaxTreeOptionsProvider: null,
metadataReferenceResolver: null,
assemblyIdentityComparer: null,
strongNameProvider: null,
metadataImportOptions: MetadataImportOptions.Public,
referencesSupersedeLowerVersions: false,
publicSign: false,
topLevelBinderFlags: BinderFlags.None,
nullableContextOptions: NullableContextOptions.Enable);
yield return defaultOptions;
yield return defaultOptions.WithNullableContextOptions(NullableContextOptions.Disable);
yield return defaultOptions.WithNullableContextOptions(NullableContextOptions.Warnings);
yield return defaultOptions.WithOptimizationLevel(OptimizationLevel.Release);
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: false, suppressSilverlightPlatformAssembliesPortability: false)));
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: true, suppressSilverlightPlatformAssembliesPortability: false)));
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: false, suppressSilverlightPlatformAssembliesPortability: true)));
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: true, suppressSilverlightPlatformAssembliesPortability: true)));
}
private static IEnumerable<CSharpParseOptions> GetCSharpParseOptions()
{
var parseOptions = new CSharpParseOptions(
languageVersion: LanguageVersion.CSharp8,
kind: SourceCodeKind.Regular);
yield return parseOptions;
yield return parseOptions.WithLanguageVersion(LanguageVersion.CSharp9);
yield return parseOptions.WithLanguageVersion(LanguageVersion.Latest);
yield return parseOptions.WithLanguageVersion(LanguageVersion.Preview);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Debugging;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Roslyn.Test.Utilities.PDB;
using Roslyn.Utilities;
using TestResources.NetFX;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class CSharpDeterministicBuildCompilationTests : CSharpTestBase, IEnumerable<object[]>
{
private static void VerifyCompilationOptions(
CSharpCompilationOptions originalOptions,
Compilation compilation,
EmitOptions emitOptions,
BlobReader compilationOptionsBlobReader,
string langVersion,
int sourceFileCount)
{
var pdbOptions = DeterministicBuildCompilationTestHelpers.ParseCompilationOptions(compilationOptionsBlobReader);
DeterministicBuildCompilationTestHelpers.AssertCommonOptions(emitOptions, originalOptions, compilation, pdbOptions);
// See CSharpCompilation.SerializeForPdb to see options that are included
pdbOptions.VerifyPdbOption("nullable", originalOptions.NullableContextOptions);
pdbOptions.VerifyPdbOption("checked", originalOptions.CheckOverflow);
pdbOptions.VerifyPdbOption("unsafe", originalOptions.AllowUnsafe);
Assert.Equal(langVersion, pdbOptions["language-version"]);
Assert.Equal(sourceFileCount.ToString(), pdbOptions["source-file-count"]);
var firstSyntaxTree = (CSharpSyntaxTree)compilation.SyntaxTrees.FirstOrDefault();
pdbOptions.VerifyPdbOption("define", firstSyntaxTree.Options.PreprocessorSymbolNames, isDefault: v => v.IsEmpty(), toString: v => string.Join(",", v));
}
private static void TestDeterministicCompilationCSharp(
string langVersion,
SyntaxTree[] syntaxTrees,
CSharpCompilationOptions compilationOptions,
EmitOptions emitOptions,
TestMetadataReferenceInfo[] metadataReferences,
int? debugDocumentsCount = null)
{
var targetFramework = TargetFramework.NetCoreApp;
var originalCompilation = CreateCompilation(
syntaxTrees,
references: metadataReferences.SelectAsArray(r => r.MetadataReference),
options: compilationOptions,
targetFramework: targetFramework);
var peBlob = originalCompilation.EmitToArray(options: emitOptions);
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.Reproducible, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var reproducible = entries[2];
var embedded = entries[3];
using (var embeddedPdb = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var pdbReader = embeddedPdb.GetMetadataReader();
var metadataReferenceReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationMetadataReferences, pdbReader);
var compilationOptionsReader = DeterministicBuildCompilationTestHelpers.GetSingleBlob(PortableCustomDebugInfoKinds.CompilationOptions, pdbReader);
Assert.Equal(debugDocumentsCount ?? syntaxTrees.Length, pdbReader.Documents.Count);
VerifyCompilationOptions(compilationOptions, originalCompilation, emitOptions, compilationOptionsReader, langVersion, syntaxTrees.Length);
DeterministicBuildCompilationTestHelpers.VerifyReferenceInfo(metadataReferences, targetFramework, metadataReferenceReader);
}
}
}
[Theory]
[ClassData(typeof(CSharpDeterministicBuildCompilationTests))]
public void PortablePdb_DeterministicCompilation(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
{
var sourceOne = Parse(@"
using System;
class MainType
{
public static void Main()
{
Console.WriteLine();
}
}
", filename: "a.cs", options: parseOptions, encoding: Encoding.UTF8);
var sourceTwo = Parse(@"
class TypeTwo
{
}", filename: "b.cs", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var sourceThree = Parse(@"
class TypeThree
{
}", filename: "c.cs", options: parseOptions, encoding: Encoding.Unicode);
var referenceOneCompilation = CreateCompilation(
@"public struct StructWithReference
{
string PrivateData;
}
public struct StructWithValue
{
int PrivateData;
}", options: TestOptions.DebugDll);
var referenceTwoCompilation = CreateCompilation(
@"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);
using var referenceOne = TestMetadataReferenceInfo.Create(
referenceOneCompilation,
fullPath: "abcd.dll",
emitOptions: emitOptions);
using var referenceTwo = TestMetadataReferenceInfo.Create(
referenceTwoCompilation,
fullPath: "efgh.dll",
emitOptions: emitOptions);
var testSource = new[] { sourceOne, sourceTwo, sourceThree };
TestDeterministicCompilationCSharp(
parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(),
testSource,
compilationOptions,
emitOptions,
new[] { referenceOne, referenceTwo });
}
[Theory]
[ClassData(typeof(CSharpDeterministicBuildCompilationTests))]
public void PortablePdb_DeterministicCompilation_DuplicateFilePaths(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
{
var sourceOne = Parse(@"
using System;
class MainType
{
public static void Main()
{
Console.WriteLine();
}
}
", filename: "a.cs", options: parseOptions, encoding: Encoding.UTF8);
var sourceTwo = Parse(@"
class TypeTwo
{
}", filename: "b.cs", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var sourceThree = Parse(@"
class TypeThree
{
}", filename: "a.cs", options: parseOptions, encoding: Encoding.Unicode);
var referenceOneCompilation = CreateCompilation(
@"public struct StructWithReference
{
string PrivateData;
}
public struct StructWithValue
{
int PrivateData;
}", options: TestOptions.DebugDll);
var referenceTwoCompilation = CreateCompilation(
@"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);
using var referenceOne = TestMetadataReferenceInfo.Create(
referenceOneCompilation,
fullPath: "abcd.dll",
emitOptions: emitOptions);
using var referenceTwo = TestMetadataReferenceInfo.Create(
referenceTwoCompilation,
fullPath: "efgh.dll",
emitOptions: emitOptions);
var testSource = new[] { sourceOne, sourceTwo, sourceThree };
// Note that only one debug document can be present for each distinct source path.
// So if more than one syntax tree has the same file path, it won't be possible to do a rebuild from the DLL+PDB.
TestDeterministicCompilationCSharp(
parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(),
testSource,
compilationOptions,
emitOptions,
new[] { referenceOne, referenceTwo },
debugDocumentsCount: 2);
}
[ConditionalTheory(typeof(DesktopOnly))]
[ClassData(typeof(CSharpDeterministicBuildCompilationTests))]
public void PortablePdb_DeterministicCompilationWithSJIS(CSharpCompilationOptions compilationOptions, EmitOptions emitOptions, CSharpParseOptions parseOptions)
{
var sourceOne = Parse(@"
using System;
class MainType
{
public static void Main()
{
Console.WriteLine();
}
}
", filename: "a.cs", options: parseOptions, encoding: Encoding.UTF8);
var sourceTwo = Parse(@"
class TypeTwo
{
}", filename: "b.cs", options: parseOptions, encoding: new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
var sourceThree = Parse(@"
class TypeThree
{
}", filename: "c.cs", options: parseOptions, encoding: Encoding.GetEncoding(932)); // SJIS encoding
var referenceOneCompilation = CreateCompilation(
@"public struct StructWithReference
{
string PrivateData;
}
public struct StructWithValue
{
int PrivateData;
}", options: TestOptions.DebugDll);
var referenceTwoCompilation = CreateCompilation(
@"public class ReferenceTwo
{
}", options: TestOptions.DebugDll);
using var referenceOne = TestMetadataReferenceInfo.Create(
referenceOneCompilation,
fullPath: "abcd.dll",
emitOptions: emitOptions);
using var referenceTwo = TestMetadataReferenceInfo.Create(
referenceTwoCompilation,
fullPath: "efgh.dll",
emitOptions: emitOptions);
var testSource = new[] { sourceOne, sourceTwo, sourceThree };
TestDeterministicCompilationCSharp(
parseOptions.LanguageVersion.MapSpecifiedToEffectiveVersion().ToDisplayString(),
testSource,
compilationOptions,
emitOptions,
new[] { referenceOne, referenceTwo });
}
public IEnumerator<object[]> GetEnumerator() => GetTestParameters().GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
private static IEnumerable<object[]> GetTestParameters()
{
foreach (var compilationOptions in GetCompilationOptions())
{
foreach (var emitOptions in DeterministicBuildCompilationTestHelpers.GetEmitOptions())
{
foreach (var parseOptions in GetCSharpParseOptions())
{
yield return new object[] { compilationOptions, emitOptions, parseOptions };
}
}
}
}
private static IEnumerable<CSharpCompilationOptions> GetCompilationOptions()
{
// Provide non default options for to test that they are being serialized
// to the pdb correctly. It needs to produce a compilation to be emitted, but otherwise
// everything should be non-default if possible. Diagnostic settings are ignored
// because they won't be serialized.
// Use constructor that requires all arguments. If new arguments are added, it's possible they need to be
// included in the pdb serialization and added to tests here
var defaultOptions = new CSharpCompilationOptions(
OutputKind.ConsoleApplication,
reportSuppressedDiagnostics: false,
moduleName: "Module",
mainTypeName: "MainType",
scriptClassName: null,
usings: new[] { "System", "System.Threading" },
optimizationLevel: OptimizationLevel.Debug,
checkOverflow: true,
allowUnsafe: true,
cryptoKeyContainer: null,
cryptoKeyFile: null,
cryptoPublicKey: default,
delaySign: null,
platform: Platform.AnyCpu,
generalDiagnosticOption: ReportDiagnostic.Default,
warningLevel: 4,
specificDiagnosticOptions: null,
concurrentBuild: true,
deterministic: true,
currentLocalTime: default,
debugPlusMode: false,
xmlReferenceResolver: null,
sourceReferenceResolver: null,
syntaxTreeOptionsProvider: null,
metadataReferenceResolver: null,
assemblyIdentityComparer: null,
strongNameProvider: null,
metadataImportOptions: MetadataImportOptions.Public,
referencesSupersedeLowerVersions: false,
publicSign: false,
topLevelBinderFlags: BinderFlags.None,
nullableContextOptions: NullableContextOptions.Enable);
yield return defaultOptions;
yield return defaultOptions.WithNullableContextOptions(NullableContextOptions.Disable);
yield return defaultOptions.WithNullableContextOptions(NullableContextOptions.Warnings);
yield return defaultOptions.WithOptimizationLevel(OptimizationLevel.Release);
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: false, suppressSilverlightPlatformAssembliesPortability: false)));
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: true, suppressSilverlightPlatformAssembliesPortability: false)));
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: false, suppressSilverlightPlatformAssembliesPortability: true)));
yield return defaultOptions.WithAssemblyIdentityComparer(new DesktopAssemblyIdentityComparer(new AssemblyPortabilityPolicy(suppressSilverlightLibraryAssembliesPortability: true, suppressSilverlightPlatformAssembliesPortability: true)));
}
private static IEnumerable<CSharpParseOptions> GetCSharpParseOptions()
{
var parseOptions = new CSharpParseOptions(
languageVersion: LanguageVersion.CSharp8,
kind: SourceCodeKind.Regular);
yield return parseOptions;
yield return parseOptions.WithLanguageVersion(LanguageVersion.CSharp9);
yield return parseOptions.WithLanguageVersion(LanguageVersion.Latest);
yield return parseOptions.WithLanguageVersion(LanguageVersion.Preview);
}
}
}
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/VisualBasic/Test/IOperation/IOperation/IOperationTests_ISymbolInitializer.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.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub NoInitializers()
Dim source = <compilation>
<file name="c.vb">
<![CDATA[
Class C
Shared s1 As Integer
Private i1 As Integer
Private Property P1 As Integer
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.Regular)
Dim tree = compilation.SyntaxTrees.Single()
Dim nodes = tree.GetRoot().DescendantNodes().Where(Function(n) TryCast(n, VariableDeclaratorSyntax) IsNot Nothing OrElse TryCast(n, PropertyStatementSyntax) IsNot Nothing).ToArray()
Assert.Equal(3, nodes.Length)
Dim semanticModel = compilation.GetSemanticModel(tree)
For Each node In nodes
Assert.Null(semanticModel.GetOperation(node))
Next
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_StaticField()
Dim source = <![CDATA[
Class C
Shared s1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_InstanceField()
Dim source = <![CDATA[
Class C
Private i1 As Integer = 1, i2 As Integer = 2'BIND:"= 2"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.i2 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_Property()
Dim source = <![CDATA[
Class C
Private Property P1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (Property: Property C.P1 As System.Int32) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= 1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_DefaultValueParameter()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IParameterInitializerOperation (Parameter: [p1 As System.Int32 = 0]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30642: 'Optional' and 'ParamArray' cannot be combined.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0"
~~~~~~~~~~
BC30046: Method cannot have both a ParamArray and Optional parameters.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_DefaultValueParamsArray()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IParameterInitializerOperation (Parameter: [ParamArray p2 As System.Int32() = Nothing]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= Nothing')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32(), Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30642: 'Optional' and 'ParamArray' cannot be combined.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing"
~~~~~~~~~~
BC30046: Method cannot have both a ParamArray and Optional parameters.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub AsNewFieldInitializer()
Dim source = <![CDATA[
Class C
Dim x As New Object'BIND:"As New Object"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.x As System.Object) (OperationKind.FieldInitializer, Type: null) (Syntax: 'As New Object')
IObjectCreationOperation (Constructor: Sub System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object) (Syntax: 'New Object')
Arguments(0)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub MultipleFieldInitializers()
Dim source = <![CDATA[
Class C
Dim x, y As New Object'BIND:"As New Object"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (2 initialized fields) (OperationKind.FieldInitializer, Type: null) (Syntax: 'As New Object')
Field_1: C.x As System.Object
Field_2: C.y As System.Object
IObjectCreationOperation (Constructor: Sub System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object) (Syntax: 'New Object')
Arguments(0)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub SingleFieldInitializerErrorCase()
Dim source = <![CDATA[
Class C1
Dim x, y As Object = Me'BIND:"= Me"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (2 initialized fields) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Me')
Field_1: C1.x As System.Object
Field_2: C1.y As System.Object
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'Me')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsInvalid) (Syntax: 'Me')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier.
Dim x, y As Object = Me'BIND:"= Me"
~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub MultipleWithEventsInitializers()
Dim source = <![CDATA[
Class C1
Public Sub New(c As C1)
End Sub
WithEvents e, f As New C1(Me)'BIND:"As New C1(Me)"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (2 initialized properties) (OperationKind.PropertyInitializer, Type: null) (Syntax: 'As New C1(Me)')
Property_1: WithEvents C1.e As C1
Property_2: WithEvents C1.f As C1
IObjectCreationOperation (Constructor: Sub C1..ctor(c As C1)) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1(Me)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'Me')
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'Me')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub SingleWithEventsInitializersErrorCase()
Dim source = <![CDATA[
Class C1
Public Sub New(c As C1)
End Sub
WithEvents e, f As C1 = Me'BIND:"= Me"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (2 initialized properties) (OperationKind.PropertyInitializer, Type: null, IsInvalid) (Syntax: '= Me')
Property_1: WithEvents C1.e As C1
Property_2: WithEvents C1.f As C1
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsInvalid) (Syntax: 'Me')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier.
WithEvents e, f As C1 = Me'BIND:"= Me"
~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ExpressionInitializers_StaticField()
Dim source = <![CDATA[
Class C
Shared s1 As Integer = 1 + F()'BIND:"= 1 + F()"
Private Shared Function F() As Integer
Return 1
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1 + F()')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '1 + F()')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
IInvocationOperation (Function C.F() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ExpressionInitializers_InstanceField()
Dim source = <![CDATA[
Class C
Private i1 As Integer = 1 + F()'BIND:"= 1 + F()"
Private Shared Function F() As Integer
Return 1
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.i1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1 + F()')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '1 + F()')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
IInvocationOperation (Function C.F() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ExpressionInitializers_Property()
Dim source = <![CDATA[
Class C
Private Property P1 As Integer = 1 + F()'BIND:"= 1 + F()"
Private Shared Function F() As Integer
Return 1
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (Property: Property C.P1 As System.Int32) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= 1 + F()')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '1 + F()')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
IInvocationOperation (Function C.F() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub PartialClasses_StaticField()
Dim source = <![CDATA[
Partial Class C
Shared s1 As Integer = 1'BIND:"= 1"
Private i1 As Integer = 1
End Class
Partial Class C
Shared s2 As Integer = 2
Private i2 As Integer = 2
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub PartialClasses_InstanceField()
Dim source = <![CDATA[
Partial Class C
Shared s1 As Integer = 1
Private i1 As Integer = 1
End Class
Partial Class C
Shared s2 As Integer = 2
Private i2 As Integer = 2'BIND:"= 2"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.i2 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")>
Public Sub FieldInitializer_ConstantConversions_01()
Dim source = <![CDATA[
Option Strict On
Class C
Private s1 As Byte = 0.0'BIND:"= 0.0"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Byte) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= 0.0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Byte'.
Private s1 As Byte = 0.0'BIND:"= 0.0"
~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")>
Public Sub FieldInitializer_ConstantConversions_02()
Dim source = <![CDATA[
Option Strict On
Class C
Private s1 As Byte = 0'BIND:"= 0"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Byte) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 0, IsImplicit) (Syntax: '0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantInitializer_NonConstantField()
Dim source = <![CDATA[
Class C
Shared s1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantInitializer_NonConstantStaticField()
' This unit test also includes declaration with multiple variables.
Dim source = <![CDATA[
Class C
Shared s0 As Integer = 0, s1 As Integer = M(), s2 As Integer 'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
null
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantInitializer_NonConstantInstanceField()
Dim source = <![CDATA[
Class C
Private s1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= M()')
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M()')
Instance Receiver:
null
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Const s1 As Integer = M()'BIND:"= M()"
~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_AsNewFieldInitializer()
Dim source = <![CDATA[
Class C
Private s1, s2 As New Integer()'BIND:"As New Integer()"
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New Integer()')
Right:
IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()')
Arguments(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Left:
IFieldReferenceOperation: C.s2 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New Integer()')
Right:
IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ArrayDeclaration()
Dim source = <![CDATA[
Class C
Private s1(10) As Integer = Nothing'BIND:"= Nothing"
End Class
]]>.Value
' Expected Flow graph should also include the implicit array initializer (10).
' This is tracked by https://github.com/dotnet/roslyn/issues/26780
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsImplicit) (Syntax: '= Nothing')
Left:
IFieldReferenceOperation: C.s1 As System.Int32() (OperationKind.FieldReference, Type: System.Int32(), IsImplicit) (Syntax: '= Nothing')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= Nothing')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32(), Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNothingLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Private s1(10) As Integer = Nothing'BIND:"= Nothing"
~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_ConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = If(True, 1, 2)'BIND:"= If(True, 1, 2)"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block [UnReachable]
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(True, 1, 2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= If(True, 1, 2)')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(True, 1, 2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantInitializer_NonConstantStaticField()
Dim source = <![CDATA[
Class C
Private Shared s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantInitializer_NonConstantInstanceField()
Dim source = <![CDATA[
Class C
Private s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= If(M(), M2)')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32), IsInvalid) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M(), M2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M(), M2)')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(M(), M2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Const s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_AsNewFieldInitializer()
Dim source = <![CDATA[
Class C
Private s1, s2 As New C(If(a, b))'BIND:"As New C(If(a, b))"
Private Shared a As Integer? = 1
Private Shared b As Integer = 1
Public Sub New(a As Integer)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IFieldReferenceOperation: C.s1 As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B5]
Leaving: {R1}
Entering: {R3} {R4}
}
.locals {R3}
{
CaptureIds: [3]
.locals {R4}
{
CaptureIds: [2]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R4}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IFieldReferenceOperation: C.s2 As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_MissingFieldInitializerValue()
Dim source = <![CDATA[
Class C
Public s1 As Integer = 'BIND:"="
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= ')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= ')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: '= ')
Right:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Public s1 As Integer = 'BIND:"="
~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantPropertyInitializer_StaticProperty()
Dim source = <![CDATA[
Class C
Shared Property P1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantPropertyInitializer_InstanceProperty()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantPropertyInitializer_StaticProperty()
Dim source = <![CDATA[
Class C
Shared Property P1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
null
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantPropertyInitializer_InstanceProperty()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= M()')
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_PropertyInitializerWithArguments()
Dim source = <![CDATA[
Class C
Shared Property P1(i As Integer) As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IPropertyReferenceOperation: Property C.P1(i As System.Int32) As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '= 1')
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Children(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36759: Auto-implemented properties cannot have parameters.
Shared Property P1(i As Integer) As Integer = 1'BIND:"= 1"
~~~~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_AsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
Private ReadOnly Property P1 As New Integer()'BIND:"As New Integer()"
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Left:
IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New Integer()')
Right:
IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_WithEventsAsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
WithEvents e, f As New C() 'BIND:"As New C()"
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C()')
Left:
IPropertyReferenceOperation: WithEvents C.e As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C()')
Arguments(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C()')
Left:
IPropertyReferenceOperation: WithEvents C.f As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantPropertyInitializer_StaticProperty()
Dim source = <![CDATA[
Class C
Shared Property P1 As Integer = If(M(), M2())'BIND:"= If(M(), M2())"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2()')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2())')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantPropertyInitializer_InstanceProperty()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer = If(M(), M2())'BIND:"= If(M(), M2())"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2()')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= If(M(), M2())')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2())')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_AsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
Private ReadOnly Property P1 As New C(If(a, b))'BIND:"As New C(If(a, b))"
Private Shared a As Integer? = 1
Private Shared b As Integer = 1
Public Sub New(a As Integer)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IPropertyReferenceOperation: ReadOnly Property C.P1 As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_WithEventsAsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
WithEvents e, f As New C(If(a, b)) 'BIND:"As New C(If(a, b))"
Private Shared a As Integer? = 1
Private Shared b As Integer = 1
Public Sub New(a As Integer)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IPropertyReferenceOperation: WithEvents C.e As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B5]
Leaving: {R1}
Entering: {R3} {R4}
}
.locals {R3}
{
CaptureIds: [3]
.locals {R4}
{
CaptureIds: [2]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R4}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IPropertyReferenceOperation: WithEvents C.f As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_MissingPropertyInitializerValue()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer ='BIND:"="
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: '=')
Right:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Public Property P1 As Integer ='BIND:"="
~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantParameterInitializer()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = 1)'BIND:"= 1"
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantParameterInitializer()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = M1())'BIND:"= M1()"
End Sub
Private Shared Function M1() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M1()')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M1()')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M1()')
Children(1):
IInvocationOperation (Function C.M1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M1()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Private Sub M(Optional p1 As Integer = M1())'BIND:"= M1()"
~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantParameterInitializer()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = If(M1(), M2()))'BIND:"= If(M1(), M2())"
End Sub
Private Shared Function M1() As Integer?
Return 0
End Function
Private Shared Function M2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M1()')
Value:
IInvocationOperation (Function C.M1() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32), IsInvalid) (Syntax: 'M1()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'M1()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M1()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M1()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M1()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M1()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M1(), M2())')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M1(), M2())')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(M1(), M2())')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(M1(), M2())')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Private Sub M(Optional p1 As Integer = If(M1(), M2()))'BIND:"= If(M1(), M2())"
~~~~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_MissingParameterInitializerValue()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer =)'BIND:"="
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Right:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Private Sub M(Optional p1 As Integer =)'BIND:"="
~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
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.Operations
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Roslyn.Test.Utilities
Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests.Semantics
Partial Public Class IOperationTests
Inherits SemanticModelTestBase
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub NoInitializers()
Dim source = <compilation>
<file name="c.vb">
<![CDATA[
Class C
Shared s1 As Integer
Private i1 As Integer
Private Property P1 As Integer
End Class
]]>
</file>
</compilation>
Dim compilation = CreateCompilationWithMscorlib40(source, options:=TestOptions.ReleaseDll, parseOptions:=TestOptions.Regular)
Dim tree = compilation.SyntaxTrees.Single()
Dim nodes = tree.GetRoot().DescendantNodes().Where(Function(n) TryCast(n, VariableDeclaratorSyntax) IsNot Nothing OrElse TryCast(n, PropertyStatementSyntax) IsNot Nothing).ToArray()
Assert.Equal(3, nodes.Length)
Dim semanticModel = compilation.GetSemanticModel(tree)
For Each node In nodes
Assert.Null(semanticModel.GetOperation(node))
Next
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_StaticField()
Dim source = <![CDATA[
Class C
Shared s1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_InstanceField()
Dim source = <![CDATA[
Class C
Private i1 As Integer = 1, i2 As Integer = 2'BIND:"= 2"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.i2 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_Property()
Dim source = <![CDATA[
Class C
Private Property P1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (Property: Property C.P1 As System.Int32) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= 1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_DefaultValueParameter()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IParameterInitializerOperation (Parameter: [p1 As System.Int32 = 0]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= 0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30642: 'Optional' and 'ParamArray' cannot be combined.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0"
~~~~~~~~~~
BC30046: Method cannot have both a ParamArray and Optional parameters.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= 0"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ConstantInitializers_DefaultValueParamsArray()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing"
End Sub
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IParameterInitializerOperation (Parameter: [ParamArray p2 As System.Int32() = Nothing]) (OperationKind.ParameterInitializer, Type: null) (Syntax: '= Nothing')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32(), Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30642: 'Optional' and 'ParamArray' cannot be combined.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing"
~~~~~~~~~~
BC30046: Method cannot have both a ParamArray and Optional parameters.
Private Sub M(Optional p1 As Integer = 0, Optional ParamArray p2 As Integer() = Nothing)'BIND:"= Nothing"
~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub AsNewFieldInitializer()
Dim source = <![CDATA[
Class C
Dim x As New Object'BIND:"As New Object"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.x As System.Object) (OperationKind.FieldInitializer, Type: null) (Syntax: 'As New Object')
IObjectCreationOperation (Constructor: Sub System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object) (Syntax: 'New Object')
Arguments(0)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub MultipleFieldInitializers()
Dim source = <![CDATA[
Class C
Dim x, y As New Object'BIND:"As New Object"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (2 initialized fields) (OperationKind.FieldInitializer, Type: null) (Syntax: 'As New Object')
Field_1: C.x As System.Object
Field_2: C.y As System.Object
IObjectCreationOperation (Constructor: Sub System.Object..ctor()) (OperationKind.ObjectCreation, Type: System.Object) (Syntax: 'New Object')
Arguments(0)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub SingleFieldInitializerErrorCase()
Dim source = <![CDATA[
Class C1
Dim x, y As Object = Me'BIND:"= Me"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (2 initialized fields) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= Me')
Field_1: C1.x As System.Object
Field_2: C1.y As System.Object
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'Me')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsInvalid) (Syntax: 'Me')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier.
Dim x, y As Object = Me'BIND:"= Me"
~~~~~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub MultipleWithEventsInitializers()
Dim source = <![CDATA[
Class C1
Public Sub New(c As C1)
End Sub
WithEvents e, f As New C1(Me)'BIND:"As New C1(Me)"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (2 initialized properties) (OperationKind.PropertyInitializer, Type: null) (Syntax: 'As New C1(Me)')
Property_1: WithEvents C1.e As C1
Property_2: WithEvents C1.f As C1
IObjectCreationOperation (Constructor: Sub C1..ctor(c As C1)) (OperationKind.ObjectCreation, Type: C1) (Syntax: 'New C1(Me)')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: c) (OperationKind.Argument, Type: null) (Syntax: 'Me')
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1) (Syntax: 'Me')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17813, "https://github.com/dotnet/roslyn/issues/17813")>
Public Sub SingleWithEventsInitializersErrorCase()
Dim source = <![CDATA[
Class C1
Public Sub New(c As C1)
End Sub
WithEvents e, f As C1 = Me'BIND:"= Me"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (2 initialized properties) (OperationKind.PropertyInitializer, Type: null, IsInvalid) (Syntax: '= Me')
Property_1: WithEvents C1.e As C1
Property_2: WithEvents C1.f As C1
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C1, IsInvalid) (Syntax: 'Me')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30671: Explicit initialization is not permitted with multiple variables declared with a single type specifier.
WithEvents e, f As C1 = Me'BIND:"= Me"
~~~~~~~~~~~~~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ExpressionInitializers_StaticField()
Dim source = <![CDATA[
Class C
Shared s1 As Integer = 1 + F()'BIND:"= 1 + F()"
Private Shared Function F() As Integer
Return 1
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1 + F()')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '1 + F()')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
IInvocationOperation (Function C.F() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ExpressionInitializers_InstanceField()
Dim source = <![CDATA[
Class C
Private i1 As Integer = 1 + F()'BIND:"= 1 + F()"
Private Shared Function F() As Integer
Return 1
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.i1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1 + F()')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '1 + F()')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
IInvocationOperation (Function C.F() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub ExpressionInitializers_Property()
Dim source = <![CDATA[
Class C
Private Property P1 As Integer = 1 + F()'BIND:"= 1 + F()"
Private Shared Function F() As Integer
Return 1
End Function
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IPropertyInitializerOperation (Property: Property C.P1 As System.Int32) (OperationKind.PropertyInitializer, Type: null) (Syntax: '= 1 + F()')
IBinaryOperation (BinaryOperatorKind.Add, Checked) (OperationKind.Binary, Type: System.Int32) (Syntax: '1 + F()')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Right:
IInvocationOperation (Function C.F() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'F()')
Instance Receiver:
null
Arguments(0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub PartialClasses_StaticField()
Dim source = <![CDATA[
Partial Class C
Shared s1 As Integer = 1'BIND:"= 1"
Private i1 As Integer = 1
End Class
Partial Class C
Shared s2 As Integer = 2
Private i2 As Integer = 2
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(17595, "https://github.com/dotnet/roslyn/issues/17595")>
Public Sub PartialClasses_InstanceField()
Dim source = <![CDATA[
Partial Class C
Shared s1 As Integer = 1
Private i1 As Integer = 1
End Class
Partial Class C
Shared s2 As Integer = 2
Private i2 As Integer = 2'BIND:"= 2"
End Class]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.i2 As System.Int32) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")>
Public Sub FieldInitializer_ConstantConversions_01()
Dim source = <![CDATA[
Option Strict On
Class C
Private s1 As Byte = 0.0'BIND:"= 0.0"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Byte) (OperationKind.FieldInitializer, Type: null, IsInvalid) (Syntax: '= 0.0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 0, IsInvalid, IsImplicit) (Syntax: '0.0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Double, Constant: 0, IsInvalid) (Syntax: '0.0')
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30512: Option Strict On disallows implicit conversions from 'Double' to 'Byte'.
Private s1 As Byte = 0.0'BIND:"= 0.0"
~~~
]]>.Value
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation)>
<Fact, WorkItem(7299, "https://github.com/dotnet/roslyn/issues/7299")>
Public Sub FieldInitializer_ConstantConversions_02()
Dim source = <![CDATA[
Option Strict On
Class C
Private s1 As Byte = 0'BIND:"= 0"
End Class
]]>.Value
Dim expectedOperationTree = <![CDATA[
IFieldInitializerOperation (Field: C.s1 As System.Byte) (OperationKind.FieldInitializer, Type: null) (Syntax: '= 0')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Byte, Constant: 0, IsImplicit) (Syntax: '0')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: True, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyOperationTreeAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedOperationTree, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantInitializer_NonConstantField()
Dim source = <![CDATA[
Class C
Shared s1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantInitializer_NonConstantStaticField()
' This unit test also includes declaration with multiple variables.
Dim source = <![CDATA[
Class C
Shared s0 As Integer = 0, s1 As Integer = M(), s2 As Integer 'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
null
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantInitializer_NonConstantInstanceField()
Dim source = <![CDATA[
Class C
Private s1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= M()')
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M()')
Instance Receiver:
null
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Const s1 As Integer = M()'BIND:"= M()"
~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_AsNewFieldInitializer()
Dim source = <![CDATA[
Class C
Private s1, s2 As New Integer()'BIND:"As New Integer()"
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New Integer()')
Right:
IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()')
Arguments(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Left:
IFieldReferenceOperation: C.s2 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New Integer()')
Right:
IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ArrayDeclaration()
Dim source = <![CDATA[
Class C
Private s1(10) As Integer = Nothing'BIND:"= Nothing"
End Class
]]>.Value
' Expected Flow graph should also include the implicit array initializer (10).
' This is tracked by https://github.com/dotnet/roslyn/issues/26780
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32(), IsImplicit) (Syntax: '= Nothing')
Left:
IFieldReferenceOperation: C.s1 As System.Int32() (OperationKind.FieldReference, Type: System.Int32(), IsImplicit) (Syntax: '= Nothing')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= Nothing')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32(), Constant: null, IsImplicit) (Syntax: 'Nothing')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(WideningNothingLiteral)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'Nothing')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30672: Explicit initialization is not permitted for arrays declared with explicit bounds.
Private s1(10) As Integer = Nothing'BIND:"= Nothing"
~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_ConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = If(True, 1, 2)'BIND:"= If(True, 1, 2)"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'True')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B4]
Block[B3] - Block [UnReachable]
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '2')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(True, 1, 2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= If(True, 1, 2)')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'If(True, 1, 2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantInitializer_NonConstantStaticField()
Dim source = <![CDATA[
Class C
Private Shared s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantInitializer_NonConstantInstanceField()
Dim source = <![CDATA[
Class C
Private s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2)')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= If(M(), M2)')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantInitializer_ConstantField()
Dim source = <![CDATA[
Class C
Const s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32), IsInvalid) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M(), M2)')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M(), M2)')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(M(), M2)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Const s1 As Integer = If(M(), M2)'BIND:"= If(M(), M2)"
~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_AsNewFieldInitializer()
Dim source = <![CDATA[
Class C
Private s1, s2 As New C(If(a, b))'BIND:"As New C(If(a, b))"
Private Shared a As Integer? = 1
Private Shared b As Integer = 1
Public Sub New(a As Integer)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IFieldReferenceOperation: C.s1 As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B5]
Leaving: {R1}
Entering: {R3} {R4}
}
.locals {R3}
{
CaptureIds: [3]
.locals {R4}
{
CaptureIds: [2]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R4}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IFieldReferenceOperation: C.s2 As C (OperationKind.FieldReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_MissingFieldInitializerValue()
Dim source = <![CDATA[
Class C
Public s1 As Integer = 'BIND:"="
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= ')
Left:
IFieldReferenceOperation: C.s1 As System.Int32 (OperationKind.FieldReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= ')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: '= ')
Right:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Public s1 As Integer = 'BIND:"="
~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantPropertyInitializer_StaticProperty()
Dim source = <![CDATA[
Class C
Shared Property P1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantPropertyInitializer_InstanceProperty()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantPropertyInitializer_StaticProperty()
Dim source = <![CDATA[
Class C
Shared Property P1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
null
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantPropertyInitializer_InstanceProperty()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer = M()'BIND:"= M()"
Public Shared Function M() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= M()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= M()')
Right:
IInvocationOperation (Function C.M() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_PropertyInitializerWithArguments()
Dim source = <![CDATA[
Class C
Shared Property P1(i As Integer) As Integer = 1'BIND:"= 1"
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IPropertyReferenceOperation: Property C.P1(i As System.Int32) As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: i) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '= 1')
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Children(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC36759: Auto-implemented properties cannot have parameters.
Shared Property P1(i As Integer) As Integer = 1'BIND:"= 1"
~~~~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_AsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
Private ReadOnly Property P1 As New Integer()'BIND:"As New Integer()"
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Left:
IPropertyReferenceOperation: ReadOnly Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'As New Integer()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New Integer()')
Right:
IObjectCreationOperation (Constructor: Sub System.Int32..ctor()) (OperationKind.ObjectCreation, Type: System.Int32) (Syntax: 'New Integer()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_WithEventsAsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
WithEvents e, f As New C() 'BIND:"As New C()"
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C()')
Left:
IPropertyReferenceOperation: WithEvents C.e As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C()')
Arguments(0)
Initializer:
null
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C()')
Left:
IPropertyReferenceOperation: WithEvents C.f As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C()')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C()')
Arguments(0)
Initializer:
null
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantPropertyInitializer_StaticProperty()
Dim source = <![CDATA[
Class C
Shared Property P1 As Integer = If(M(), M2())'BIND:"= If(M(), M2())"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2()')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (Static) (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Instance Receiver:
null
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2())')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantPropertyInitializer_InstanceProperty()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer = If(M(), M2())'BIND:"= If(M(), M2())"
Public Shared Function M() As Integer?
Return 0
End Function
Public Shared Function M2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation (Function C.M() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32)) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'M()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'M()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'M()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'M2()')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: '= If(M(), M2())')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: '= If(M(), M2())')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(M(), M2())')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_AsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
Private ReadOnly Property P1 As New C(If(a, b))'BIND:"As New C(If(a, b))"
Private Shared a As Integer? = 1
Private Shared b As Integer = 1
Public Sub New(a As Integer)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IPropertyReferenceOperation: ReadOnly Property C.P1 As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_WithEventsAsNewPropertyInitializer()
Dim source = <![CDATA[
Class C
WithEvents e, f As New C(If(a, b)) 'BIND:"As New C(If(a, b))"
Private Shared a As Integer? = 1
Private Shared b As Integer = 1
Public Sub New(a As Integer)
End Sub
End Class
]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IPropertyReferenceOperation: WithEvents C.e As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B5]
Leaving: {R1}
Entering: {R3} {R4}
}
.locals {R3}
{
CaptureIds: [3]
.locals {R4}
{
CaptureIds: [2]
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IFieldReferenceOperation: C.a As System.Nullable(Of System.Int32) (Static) (OperationKind.FieldReference, Type: System.Nullable(Of System.Int32)) (Syntax: 'a')
Instance Receiver:
null
Jump if True (Regular) to Block[B7]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'a')
Operand:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Leaving: {R4}
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'a')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'a')
Instance Receiver:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsImplicit) (Syntax: 'a')
Arguments(0)
Next (Regular) Block[B8]
Leaving: {R4}
}
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IFieldReferenceOperation: C.b As System.Int32 (Static) (OperationKind.FieldReference, Type: System.Int32) (Syntax: 'b')
Instance Receiver:
null
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Left:
IPropertyReferenceOperation: WithEvents C.f As C (OperationKind.PropertyReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'As New C(If(a, b))')
Right:
IObjectCreationOperation (Constructor: Sub C..ctor(a As System.Int32)) (OperationKind.ObjectCreation, Type: C) (Syntax: 'New C(If(a, b))')
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'If(a, b)')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'If(a, b)')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Initializer:
null
Next (Regular) Block[B9]
Leaving: {R3}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of AsNewClauseSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_MissingPropertyInitializerValue()
Dim source = <![CDATA[
Class C
Public Property P1 As Integer ='BIND:"="
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Left:
IPropertyReferenceOperation: Property C.P1 As System.Int32 (OperationKind.PropertyReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: '=')
Right:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Public Property P1 As Integer ='BIND:"="
~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_ConstantParameterInitializer()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = 1)'BIND:"= 1"
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: '= 1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = String.Empty
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_NonConstantParameterInitializer()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = M1())'BIND:"= M1()"
End Sub
Private Shared Function M1() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M1()')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= M1()')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M1()')
Children(1):
IInvocationOperation (Function C.M1() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M1()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Private Sub M(Optional p1 As Integer = M1())'BIND:"= M1()"
~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub ControlFlow_NonConstantParameterInitializer()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer = If(M1(), M2()))'BIND:"= If(M1(), M2())"
End Sub
Private Shared Function M1() As Integer?
Return 0
End Function
Private Shared Function M2() As Integer
Return 0
End Function
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2}
.locals {R1}
{
CaptureIds: [1]
.locals {R2}
{
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M1()')
Value:
IInvocationOperation (Function C.M1() As System.Nullable(Of System.Int32)) (OperationKind.Invocation, Type: System.Nullable(Of System.Int32), IsInvalid) (Syntax: 'M1()')
Instance Receiver:
null
Arguments(0)
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'M1()')
Operand:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M1()')
Leaving: {R2}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M1()')
Value:
IInvocationOperation ( Function System.Nullable(Of System.Int32).GetValueOrDefault() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'M1()')
Instance Receiver:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Nullable(Of System.Int32), IsInvalid, IsImplicit) (Syntax: 'M1()')
Arguments(0)
Next (Regular) Block[B4]
Leaving: {R2}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'M2()')
Value:
IInvocationOperation (Function C.M2() As System.Int32) (OperationKind.Invocation, Type: System.Int32, IsInvalid) (Syntax: 'M2()')
Instance Receiver:
null
Arguments(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M1(), M2())')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '= If(M1(), M2())')
Right:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(M1(), M2())')
Children(1):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'If(M1(), M2())')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30059: Constant expression is required.
Private Sub M(Optional p1 As Integer = If(M1(), M2()))'BIND:"= If(M1(), M2())"
~~~~~~~~~~~~~~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
<CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)>
<Fact>
Public Sub NoControlFlow_MissingParameterInitializerValue()
Dim source = <![CDATA[
Class C
Private Sub M(Optional p1 As Integer =)'BIND:"="
End Sub
End Class]]>.Value
Dim expectedFlowGraph = <![CDATA[
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Left:
IParameterReferenceOperation: p1 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '=')
Right:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
]]>.Value
Dim expectedDiagnostics = <![CDATA[
BC30201: Expression expected.
Private Sub M(Optional p1 As Integer =)'BIND:"="
~
]]>.Value
VerifyFlowGraphAndDiagnosticsForTest(Of EqualsValueSyntax)(source, expectedFlowGraph, expectedDiagnostics)
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 55,614 | Move NonRemappableRegions, Capabilities to EditSession | Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | tmat | 2021-08-13T18:46:58Z | 2021-08-16T16:50:03Z | 7fb7af26eafae33fa23ce72a16f42e694e3bc177 | 612b978e951f219b625f1b117d6d0f0f48a0ca55 | Move NonRemappableRegions, Capabilities to EditSession. Removes mutable NonRemappableRegions from DebuggingSession.
Makes capabilities lazy - they are only needed when analyzing documents with changes, but not before such document is analyzed.
Allows capabilities to change during debugging session - they are still immutable within edit session. When the debugger attaches to a new process it can now restart edit session with new capabilities and active statements.
Debugger follow-up: https://devdiv.visualstudio.com/DevDiv/_workitems/edit/1371922 | ./src/Compilers/Test/Resources/Core/SymbolsTests/NoPia/GeneralPia.dll | MZ @ !L!This program cannot be run in DOS mode.
$ PE L 3L ! L j @ @ j S H .text K L `.sdata W P @ .rsrc R @ @.reloc V @ B j H l" <H &(
* * (
* s
s
s
s
* 0 ~ o
+ *0 ~ o
+ *0 ~ o
+ *0 ~ o
+ *0 (
(
+ * 0 (
+ *0 (
+ *0 (
+ *0 -
( +
++
+ * 0
* * (
* 0 / {
o
-( +{
o
+ * V (
s
}
* &(
* &(
* &(+
* &(
* &(
* &(
* &(
* BSJB v4.0.30319 l $$ #~ $ #Strings 8 #US 8 #GUID 8 #Blob W %3 I D
A ! $ F
{
A{
A f } 4 H K b
K w
8" Q" ~f
Q4 f
/ C Q h y A/ X m ~ 1 P bf w *> Mf mf ) 7 : 7 E 7
O
]
x ! - - -
! )5 # J5! % W5! ) e5 - j5 1 n5 1 w5 7 5 9 A E
M N S
[ \ _ = b # c >! i B m b n
p q s s - s - s ! @- s \ ! s \ ! u f\ ! x sz ! z z ! | z ! z ! z ! z ! z ! z ! z
! !
!
!
!
* ! <* ! Y* ! g* ! 1 1 -- 1 O: 1 tG ! P k Vs Vx k Vs V Vx V Vf V0 > P T g l Vq s x k V"%V&%k V"*V&** ,/ q3P \ h ( F5 dB ! Fc $! Fh <! l X! Fq p! x ! ! ! " F F
F F>
Fzq F~ F F F F F F F F> Fz0 F>= FzJ! F+T$ F7Y$ % Fd' F + Fo, . Fv0 F 4 F5 FW7 Fh7 Fl9 F9 F9 F 9 F 9 F 9 F 9 F 9 F9 F: F; F< |