repo_name
stringclasses 6
values | pr_number
int64 512
78.9k
| pr_title
stringlengths 3
144
| pr_description
stringlengths 0
30.3k
| author
stringlengths 2
21
| date_created
unknown | date_merged
unknown | previous_commit
stringlengths 40
40
| pr_commit
stringlengths 40
40
| query
stringlengths 17
30.4k
| filepath
stringlengths 9
210
| before_content
stringlengths 0
112M
| after_content
stringlengths 0
112M
| label
int64 -1
1
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/Core/Portable/Workspace/Solution/SolutionState.ICompilationTracker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
private interface ICompilationTracker
{
/// <summary>
/// Returns true if this tracker currently either points to a compilation, has an in-progress
/// compilation being computed, or has a skeleton reference. Note: this is simply a weak
/// statement about the tracker at this exact moment in time. Immediately after this returns
/// the tracker might change and may no longer have a final compilation (for example, if the
/// retainer let go of it) or might not have an in-progress compilation (for example, if the
/// background compiler finished with it).
///
/// Because of the above limitations, this should only be used by clients as a weak form of
/// information about the tracker. For example, a client may see that a tracker has no
/// compilation and may choose to throw it away knowing that it could be reconstructed at a
/// later point if necessary.
/// </summary>
bool HasCompilation { get; }
ProjectState ProjectState { get; }
ICompilationTracker Clone();
/// <summary>
/// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the
/// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see
/// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>.
/// </summary>
/// <remarks>
/// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered
/// when answering this question. In other words, if <paramref name="symbol"/> is an <see
/// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only
/// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is
/// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any
/// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for
/// any of the references of the <see cref="Compilation.References"/>.
/// </remarks>
bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary);
bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken);
bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken);
ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, bool clone = false, CancellationToken cancellationToken = default);
ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken);
Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken);
/// <summary>
/// Get a metadata reference to this compilation info's compilation with respect to
/// another project. For cross language references produce a skeletal assembly. If the
/// compilation is not available, it is built. If a skeletal assembly reference is
/// needed and does not exist, it is also built.
/// </summary>
Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken);
CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference);
ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken);
IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken);
Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken);
bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation);
SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
namespace Microsoft.CodeAnalysis
{
internal partial class SolutionState
{
private interface ICompilationTracker
{
/// <summary>
/// Returns true if this tracker currently either points to a compilation, has an in-progress
/// compilation being computed, or has a skeleton reference. Note: this is simply a weak
/// statement about the tracker at this exact moment in time. Immediately after this returns
/// the tracker might change and may no longer have a final compilation (for example, if the
/// retainer let go of it) or might not have an in-progress compilation (for example, if the
/// background compiler finished with it).
///
/// Because of the above limitations, this should only be used by clients as a weak form of
/// information about the tracker. For example, a client may see that a tracker has no
/// compilation and may choose to throw it away knowing that it could be reconstructed at a
/// later point if necessary.
/// </summary>
bool HasCompilation { get; }
ProjectState ProjectState { get; }
ICompilationTracker Clone();
/// <summary>
/// Returns <see langword="true"/> if this <see cref="Project"/>/<see cref="Compilation"/> could produce the
/// given <paramref name="symbol"/>. The symbol must be a <see cref="IAssemblySymbol"/>, <see
/// cref="IModuleSymbol"/> or <see cref="IDynamicTypeSymbol"/>.
/// </summary>
/// <remarks>
/// If <paramref name="primary"/> is true, then <see cref="Compilation.References"/> will not be considered
/// when answering this question. In other words, if <paramref name="symbol"/> is an <see
/// cref="IAssemblySymbol"/> and <paramref name="primary"/> is <see langword="true"/> then this will only
/// return true if the symbol is <see cref="Compilation.Assembly"/>. If <paramref name="primary"/> is
/// false, then it can return true if <paramref name="symbol"/> is <see cref="Compilation.Assembly"/> or any
/// of the symbols returned by <see cref="Compilation.GetAssemblyOrModuleSymbol(MetadataReference)"/> for
/// any of the references of the <see cref="Compilation.References"/>.
/// </remarks>
bool ContainsAssemblyOrModuleOrDynamic(ISymbol symbol, bool primary);
bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken);
bool? ContainsSymbolsWithNameFromDeclarationOnlyCompilation(string name, SymbolFilter filter, CancellationToken cancellationToken);
ICompilationTracker Fork(ProjectState newProject, CompilationAndGeneratorDriverTranslationAction? translate = null, bool clone = false, CancellationToken cancellationToken = default);
ICompilationTracker FreezePartialStateWithTree(SolutionState solution, DocumentState docState, SyntaxTree tree, CancellationToken cancellationToken);
Task<Compilation> GetCompilationAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentSemanticVersionAsync(SolutionState solution, CancellationToken cancellationToken);
Task<VersionStamp> GetDependentVersionAsync(SolutionState solution, CancellationToken cancellationToken);
/// <summary>
/// Get a metadata reference to this compilation info's compilation with respect to
/// another project. For cross language references produce a skeletal assembly. If the
/// compilation is not available, it is built. If a skeletal assembly reference is
/// needed and does not exist, it is also built.
/// </summary>
Task<MetadataReference> GetMetadataReferenceAsync(SolutionState solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken);
CompilationReference? GetPartialMetadataReference(ProjectState fromProject, ProjectReference projectReference);
ValueTask<TextDocumentStates<SourceGeneratedDocumentState>> GetSourceGeneratedDocumentStatesAsync(SolutionState solution, CancellationToken cancellationToken);
IEnumerable<SyntaxTree>? GetSyntaxTreesWithNameFromDeclarationOnlyCompilation(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken);
Task<bool> HasSuccessfullyLoadedAsync(SolutionState solution, CancellationToken cancellationToken);
bool TryGetCompilation([NotNullWhen(true)] out Compilation? compilation);
SourceGeneratedDocumentState? TryGetSourceGeneratedDocumentStateForAlreadyGeneratedId(DocumentId documentId);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/Core/Portable/EditAndContinue/DocumentActiveStatementChanges.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal readonly struct DocumentActiveStatementChanges
{
public readonly ImmutableArray<UnmappedActiveStatement> OldStatements;
public readonly ImmutableArray<ActiveStatement> NewStatements;
public readonly ImmutableArray<ImmutableArray<SourceFileSpan>> NewExceptionRegions;
public DocumentActiveStatementChanges(
ImmutableArray<UnmappedActiveStatement> oldSpans,
ImmutableArray<ActiveStatement> newStatements,
ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions)
{
Contract.ThrowIfFalse(oldSpans.Length == newStatements.Length);
Contract.ThrowIfFalse(oldSpans.Length == newExceptionRegions.Length);
#if DEBUG
for (var i = 0; i < oldSpans.Length; i++)
{
// old and new exception region counts must match:
Debug.Assert(oldSpans[i].ExceptionRegions.Spans.Length == newExceptionRegions[i].Length);
}
#endif
OldStatements = oldSpans;
NewStatements = newStatements;
NewExceptionRegions = newExceptionRegions;
}
public void Deconstruct(
out ImmutableArray<UnmappedActiveStatement> oldStatements,
out ImmutableArray<ActiveStatement> newStatements,
out ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions)
{
oldStatements = OldStatements;
newStatements = NewStatements;
newExceptionRegions = NewExceptionRegions;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.EditAndContinue
{
internal readonly struct DocumentActiveStatementChanges
{
public readonly ImmutableArray<UnmappedActiveStatement> OldStatements;
public readonly ImmutableArray<ActiveStatement> NewStatements;
public readonly ImmutableArray<ImmutableArray<SourceFileSpan>> NewExceptionRegions;
public DocumentActiveStatementChanges(
ImmutableArray<UnmappedActiveStatement> oldSpans,
ImmutableArray<ActiveStatement> newStatements,
ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions)
{
Contract.ThrowIfFalse(oldSpans.Length == newStatements.Length);
Contract.ThrowIfFalse(oldSpans.Length == newExceptionRegions.Length);
#if DEBUG
for (var i = 0; i < oldSpans.Length; i++)
{
// old and new exception region counts must match:
Debug.Assert(oldSpans[i].ExceptionRegions.Spans.Length == newExceptionRegions[i].Length);
}
#endif
OldStatements = oldSpans;
NewStatements = newStatements;
NewExceptionRegions = newExceptionRegions;
}
public void Deconstruct(
out ImmutableArray<UnmappedActiveStatement> oldStatements,
out ImmutableArray<ActiveStatement> newStatements,
out ImmutableArray<ImmutableArray<SourceFileSpan>> newExceptionRegions)
{
oldStatements = OldStatements;
newStatements = NewStatements;
newExceptionRegions = NewExceptionRegions;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/VisualBasic/Portable/Wrapping/ChainedExpression/VisualBasicChainedExpressionWrapper.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Indentation
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Wrapping.ChainedExpression
Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression
Friend Class VisualBasicChainedExpressionWrapper
Inherits AbstractChainedExpressionWrapper(Of NameSyntax, ArgumentListSyntax)
Public Sub New()
MyBase.New(VisualBasicIndentationService.WithoutParameterAlignmentInstance, VisualBasicSyntaxFacts.Instance)
End Sub
Protected Overrides Function GetNewLineBeforeOperatorTrivia(newLine As SyntaxTriviaList) As SyntaxTriviaList
Return newLine.InsertRange(0, {SyntaxFactory.WhitespaceTrivia(" "), SyntaxFactory.LineContinuationTrivia("_")})
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.VisualBasic.Indentation
Imports Microsoft.CodeAnalysis.VisualBasic.LanguageServices
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.Wrapping.ChainedExpression
Namespace Microsoft.CodeAnalysis.VisualBasic.Wrapping.ChainedExpression
Friend Class VisualBasicChainedExpressionWrapper
Inherits AbstractChainedExpressionWrapper(Of NameSyntax, ArgumentListSyntax)
Public Sub New()
MyBase.New(VisualBasicIndentationService.WithoutParameterAlignmentInstance, VisualBasicSyntaxFacts.Instance)
End Sub
Protected Overrides Function GetNewLineBeforeOperatorTrivia(newLine As SyntaxTriviaList) As SyntaxTriviaList
Return newLine.InsertRange(0, {SyntaxFactory.WhitespaceTrivia(" "), SyntaxFactory.LineContinuationTrivia("_")})
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/Core/Portable/PatternMatching/SimplePatternMatcher.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Globalization;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal partial class PatternMatcher
{
private sealed partial class SimplePatternMatcher : PatternMatcher
{
private PatternSegment _fullPatternSegment;
public SimplePatternMatcher(
string pattern,
CultureInfo culture,
bool includeMatchedSpans,
bool allowFuzzyMatching)
: base(includeMatchedSpans, culture, allowFuzzyMatching)
{
pattern = pattern.Trim();
_fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching);
_invalidPattern = _fullPatternSegment.IsInvalid;
}
public override void Dispose()
{
base.Dispose();
_fullPatternSegment.Dispose();
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <returns>If this was a match, a set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches)
{
if (SkipMatch(candidate))
{
return false;
}
return MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: false) ||
MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: true);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Globalization;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Collections;
namespace Microsoft.CodeAnalysis.PatternMatching
{
internal partial class PatternMatcher
{
private sealed partial class SimplePatternMatcher : PatternMatcher
{
private PatternSegment _fullPatternSegment;
public SimplePatternMatcher(
string pattern,
CultureInfo culture,
bool includeMatchedSpans,
bool allowFuzzyMatching)
: base(includeMatchedSpans, culture, allowFuzzyMatching)
{
pattern = pattern.Trim();
_fullPatternSegment = new PatternSegment(pattern, allowFuzzyMatching);
_invalidPattern = _fullPatternSegment.IsInvalid;
}
public override void Dispose()
{
base.Dispose();
_fullPatternSegment.Dispose();
}
/// <summary>
/// Determines if a given candidate string matches under a multiple word query text, as you
/// would find in features like Navigate To.
/// </summary>
/// <returns>If this was a match, a set of match types that occurred while matching the
/// patterns. If it was not a match, it returns null.</returns>
public override bool AddMatches(string candidate, ref TemporaryArray<PatternMatch> matches)
{
if (SkipMatch(candidate))
{
return false;
}
return MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: false) ||
MatchPatternSegment(candidate, in _fullPatternSegment, ref matches, fuzzyMatch: true);
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Util/XmlRenamer.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.IO
Imports <xmlns="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler">
Public Class XmlRenamer
Private ReadOnly _xDoc As XDocument
Public Sub New(xDoc As XDocument)
_xDoc = xDoc
End Sub
Public Sub Rename(renamingFile As String)
Dim namesToUpdate As List(Of NameToUpdate)
namesToUpdate = ParseUpdateList(renamingFile)
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Enumerator)
UpdateEnumerator(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Child)
UpdateChild(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Field)
UpdateField(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Kind)
UpdateNodeKind(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Class)
UpdateNodeClass(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Enum)
UpdateEnum(name)
Next
End Sub
Private Function ParseUpdateList(renamingFile As String) As List(Of NameToUpdate)
Dim namesToUpdate As New List(Of NameToUpdate)
For Each line In File.ReadLines(renamingFile)
Dim fields = line.Split({","c})
If fields.Length >= 4 AndAlso fields(0).Trim <> "" AndAlso Cleanup(fields(3)) <> "" Then
namesToUpdate.Add(New NameToUpdate With {.kind = DirectCast([Enum].Parse(GetType(UpdateKind), fields(0), True), UpdateKind),
.typeName = Cleanup(fields(1)),
.memberName = Cleanup(fields(2)),
.newName = Cleanup(fields(3))})
End If
Next
Return namesToUpdate
End Function
Private Function Cleanup(s As String) As String
s = s.Trim()
If s.StartsWith("[", StringComparison.Ordinal) AndAlso s.EndsWith("]", StringComparison.Ordinal) Then
s = s.Substring(1, s.Length - 2)
End If
If s.StartsWith("Optional", StringComparison.Ordinal) Then
s = s.Substring("Optional".Length)
End If
Return s
End Function
Private Sub UpdateNodeKind(update As NameToUpdate)
For Each node In (From n In _xDoc...<node-kind> Where n.@name = update.memberName)
node.@name = update.newName
Next
UpdateKindString(update.memberName, update.newName)
End Sub
Private Sub UpdateNodeClass(update As NameToUpdate)
For Each node In (From n In _xDoc...<node-structure> Where n.@name = update.typeName)
node.@name = update.newName
Next
For Each node In (From n In _xDoc...<node-structure> Where n.@parent = update.typeName)
node.@parent = update.newName
Next
Dim oldKindName = "@" + update.typeName
Dim newKindName = "@" + update.newName
UpdateKindString(oldKindName, newKindName)
End Sub
Private Sub UpdateEnum(update As NameToUpdate)
For Each node In (From n In _xDoc...<enumeration> Where n.@name = update.typeName)
node.@name = update.newName
Next
End Sub
Private Sub UpdateEnumerator(update As NameToUpdate)
For Each enumNode In (From n In _xDoc...<enumeration> Where n.@name = update.typeName)
For Each node In (From n In enumNode.<enumerators>.<enumerator> Where n.@name = update.memberName)
node.@name = update.newName
Next
Next
End Sub
Private Sub UpdateChild(update As NameToUpdate)
For Each structNode In (From n In _xDoc...<node-structure> Where n.@name = update.typeName)
For Each node In (From n In structNode.<child> Where n.@name = update.memberName)
node.@name = update.newName
Next
Next
End Sub
Private Sub UpdateField(update As NameToUpdate)
For Each structNode In (From n In _xDoc...<node-structure> Where n.@name = update.typeName)
For Each node In (From n In structNode.<field> Where n.@name = update.memberName)
node.@name = update.newName
Next
Next
End Sub
Private Function IndexOfNodeKind(attrValue As String, kind As String) As Integer
If String.IsNullOrEmpty(attrValue) Then
Return -1
End If
Dim index As Integer = attrValue.IndexOf(kind, StringComparison.Ordinal)
If (index > 0 AndAlso attrValue(index - 1) <> "|"c) Then
Return -1 ' must be preceded by vert bar or nothing.
End If
Dim endIndex = index + kind.Length
If (endIndex < attrValue.Length AndAlso attrValue(endIndex) <> "|"c) Then
Return -1 ' must be followed by vert bar or nothing.
End If
Return index
End Function
Private Function ContainsNodeKind(attrValue As String, kind As String) As Boolean
Return IndexOfNodeKind(attrValue, kind) >= 0
End Function
Private Sub UpdateKindString(oldKind As String, newKind As String)
For Each node In (From n In _xDoc...<child> Where ContainsNodeKind(n.@kind, oldKind))
UpdateKindAttribute(node.Attribute("kind"), oldKind, newKind)
Next
For Each node In (From n In _xDoc...<child> Where ContainsNodeKind(n.@<separator-kind>, oldKind))
UpdateKindAttribute(node.Attribute("separator-kind"), oldKind, newKind)
Next
For Each node In (From n In _xDoc...<node-kind-alias> Where ContainsNodeKind(n.@alias, oldKind))
UpdateKindAttribute(node.Attribute("alias"), oldKind, newKind)
Next
End Sub
Private Sub UpdateKindAttribute(attr As XAttribute, oldKind As String, newKind As String)
Dim attrValue = attr.Value
Dim startIndex = IndexOfNodeKind(attrValue, oldKind)
Dim newValue = attrValue.Substring(0, startIndex) + newKind + attrValue.Substring(startIndex + oldKind.Length)
attr.Value = newValue
End Sub
End Class
Friend Class NameToUpdate
Public kind As updateKind
Public typeName As String
Public memberName As String
Public newName As String
End Class
Friend Enum UpdateKind
[Enum]
Enumerator
[Class]
Kind
Field
Child
End Enum
| ' Licensed to the .NET Foundation under one or more 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.IO
Imports <xmlns="http://schemas.microsoft.com/VisualStudio/Roslyn/Compiler">
Public Class XmlRenamer
Private ReadOnly _xDoc As XDocument
Public Sub New(xDoc As XDocument)
_xDoc = xDoc
End Sub
Public Sub Rename(renamingFile As String)
Dim namesToUpdate As List(Of NameToUpdate)
namesToUpdate = ParseUpdateList(renamingFile)
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Enumerator)
UpdateEnumerator(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Child)
UpdateChild(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Field)
UpdateField(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Kind)
UpdateNodeKind(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Class)
UpdateNodeClass(name)
Next
For Each name In (From n In namesToUpdate Where n.kind = UpdateKind.Enum)
UpdateEnum(name)
Next
End Sub
Private Function ParseUpdateList(renamingFile As String) As List(Of NameToUpdate)
Dim namesToUpdate As New List(Of NameToUpdate)
For Each line In File.ReadLines(renamingFile)
Dim fields = line.Split({","c})
If fields.Length >= 4 AndAlso fields(0).Trim <> "" AndAlso Cleanup(fields(3)) <> "" Then
namesToUpdate.Add(New NameToUpdate With {.kind = DirectCast([Enum].Parse(GetType(UpdateKind), fields(0), True), UpdateKind),
.typeName = Cleanup(fields(1)),
.memberName = Cleanup(fields(2)),
.newName = Cleanup(fields(3))})
End If
Next
Return namesToUpdate
End Function
Private Function Cleanup(s As String) As String
s = s.Trim()
If s.StartsWith("[", StringComparison.Ordinal) AndAlso s.EndsWith("]", StringComparison.Ordinal) Then
s = s.Substring(1, s.Length - 2)
End If
If s.StartsWith("Optional", StringComparison.Ordinal) Then
s = s.Substring("Optional".Length)
End If
Return s
End Function
Private Sub UpdateNodeKind(update As NameToUpdate)
For Each node In (From n In _xDoc...<node-kind> Where n.@name = update.memberName)
node.@name = update.newName
Next
UpdateKindString(update.memberName, update.newName)
End Sub
Private Sub UpdateNodeClass(update As NameToUpdate)
For Each node In (From n In _xDoc...<node-structure> Where n.@name = update.typeName)
node.@name = update.newName
Next
For Each node In (From n In _xDoc...<node-structure> Where n.@parent = update.typeName)
node.@parent = update.newName
Next
Dim oldKindName = "@" + update.typeName
Dim newKindName = "@" + update.newName
UpdateKindString(oldKindName, newKindName)
End Sub
Private Sub UpdateEnum(update As NameToUpdate)
For Each node In (From n In _xDoc...<enumeration> Where n.@name = update.typeName)
node.@name = update.newName
Next
End Sub
Private Sub UpdateEnumerator(update As NameToUpdate)
For Each enumNode In (From n In _xDoc...<enumeration> Where n.@name = update.typeName)
For Each node In (From n In enumNode.<enumerators>.<enumerator> Where n.@name = update.memberName)
node.@name = update.newName
Next
Next
End Sub
Private Sub UpdateChild(update As NameToUpdate)
For Each structNode In (From n In _xDoc...<node-structure> Where n.@name = update.typeName)
For Each node In (From n In structNode.<child> Where n.@name = update.memberName)
node.@name = update.newName
Next
Next
End Sub
Private Sub UpdateField(update As NameToUpdate)
For Each structNode In (From n In _xDoc...<node-structure> Where n.@name = update.typeName)
For Each node In (From n In structNode.<field> Where n.@name = update.memberName)
node.@name = update.newName
Next
Next
End Sub
Private Function IndexOfNodeKind(attrValue As String, kind As String) As Integer
If String.IsNullOrEmpty(attrValue) Then
Return -1
End If
Dim index As Integer = attrValue.IndexOf(kind, StringComparison.Ordinal)
If (index > 0 AndAlso attrValue(index - 1) <> "|"c) Then
Return -1 ' must be preceded by vert bar or nothing.
End If
Dim endIndex = index + kind.Length
If (endIndex < attrValue.Length AndAlso attrValue(endIndex) <> "|"c) Then
Return -1 ' must be followed by vert bar or nothing.
End If
Return index
End Function
Private Function ContainsNodeKind(attrValue As String, kind As String) As Boolean
Return IndexOfNodeKind(attrValue, kind) >= 0
End Function
Private Sub UpdateKindString(oldKind As String, newKind As String)
For Each node In (From n In _xDoc...<child> Where ContainsNodeKind(n.@kind, oldKind))
UpdateKindAttribute(node.Attribute("kind"), oldKind, newKind)
Next
For Each node In (From n In _xDoc...<child> Where ContainsNodeKind(n.@<separator-kind>, oldKind))
UpdateKindAttribute(node.Attribute("separator-kind"), oldKind, newKind)
Next
For Each node In (From n In _xDoc...<node-kind-alias> Where ContainsNodeKind(n.@alias, oldKind))
UpdateKindAttribute(node.Attribute("alias"), oldKind, newKind)
Next
End Sub
Private Sub UpdateKindAttribute(attr As XAttribute, oldKind As String, newKind As String)
Dim attrValue = attr.Value
Dim startIndex = IndexOfNodeKind(attrValue, oldKind)
Dim newValue = attrValue.Substring(0, startIndex) + newKind + attrValue.Substring(startIndex + oldKind.Length)
attr.Value = newValue
End Sub
End Class
Friend Class NameToUpdate
Public kind As updateKind
Public typeName As String
Public memberName As String
Public newName As String
End Class
Friend Enum UpdateKind
[Enum]
Enumerator
[Class]
Kind
Field
Child
End Enum
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/Core/Implementation/InlineRename/CommandHandlers/AbstractRenameCommandHandler_WordDeleteHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractRenameCommandHandler :
ICommandHandler<WordDeleteToStartCommandArgs>,
ICommandHandler<WordDeleteToEndCommandArgs>
{
public CommandState GetCommandState(WordDeleteToStartCommandArgs args)
=> GetCommandState();
public CommandState GetCommandState(WordDeleteToEndCommandArgs args)
=> GetCommandState();
public bool ExecuteCommand(WordDeleteToStartCommandArgs args, CommandExecutionContext context)
=> HandleWordDeleteCommand(args.SubjectBuffer, args.TextView, deleteToStart: true);
public bool ExecuteCommand(WordDeleteToEndCommandArgs args, CommandExecutionContext context)
=> HandleWordDeleteCommand(args.SubjectBuffer, args.TextView, deleteToStart: false);
private bool HandleWordDeleteCommand(ITextBuffer subjectBuffer, ITextView view, bool deleteToStart)
{
if (_renameService.ActiveSession == null)
{
return false;
}
var caretPoint = view.GetCaretPoint(subjectBuffer);
if (caretPoint.HasValue)
{
if (_renameService.ActiveSession.TryGetContainingEditableSpan(caretPoint.Value, out var span))
{
int start = caretPoint.Value;
int end = caretPoint.Value;
if (!view.Selection.IsEmpty)
{
var selectedSpans = view.Selection.GetSnapshotSpansOnBuffer(subjectBuffer);
if (selectedSpans.Count == 1 && span.Contains(selectedSpans.Single().Span))
{
// We might want to delete past the caret's active position if there's a selection
start = selectedSpans.Single().Start;
end = selectedSpans.Single().End;
}
else
{
// we're outside of an editable span, so let this command go to the next handler
return false;
}
}
subjectBuffer.Delete(deleteToStart
? Span.FromBounds(span.Start, end)
: Span.FromBounds(start, span.End));
return true;
}
}
return false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.VisualStudio.Commanding;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
namespace Microsoft.CodeAnalysis.Editor.Implementation.InlineRename
{
internal abstract partial class AbstractRenameCommandHandler :
ICommandHandler<WordDeleteToStartCommandArgs>,
ICommandHandler<WordDeleteToEndCommandArgs>
{
public CommandState GetCommandState(WordDeleteToStartCommandArgs args)
=> GetCommandState();
public CommandState GetCommandState(WordDeleteToEndCommandArgs args)
=> GetCommandState();
public bool ExecuteCommand(WordDeleteToStartCommandArgs args, CommandExecutionContext context)
=> HandleWordDeleteCommand(args.SubjectBuffer, args.TextView, deleteToStart: true);
public bool ExecuteCommand(WordDeleteToEndCommandArgs args, CommandExecutionContext context)
=> HandleWordDeleteCommand(args.SubjectBuffer, args.TextView, deleteToStart: false);
private bool HandleWordDeleteCommand(ITextBuffer subjectBuffer, ITextView view, bool deleteToStart)
{
if (_renameService.ActiveSession == null)
{
return false;
}
var caretPoint = view.GetCaretPoint(subjectBuffer);
if (caretPoint.HasValue)
{
if (_renameService.ActiveSession.TryGetContainingEditableSpan(caretPoint.Value, out var span))
{
int start = caretPoint.Value;
int end = caretPoint.Value;
if (!view.Selection.IsEmpty)
{
var selectedSpans = view.Selection.GetSnapshotSpansOnBuffer(subjectBuffer);
if (selectedSpans.Count == 1 && span.Contains(selectedSpans.Single().Span))
{
// We might want to delete past the caret's active position if there's a selection
start = selectedSpans.Single().Start;
end = selectedSpans.Single().End;
}
else
{
// we're outside of an editable span, so let this command go to the next handler
return false;
}
}
subjectBuffer.Delete(deleteToStart
? Span.FromBounds(span.Start, end)
: Span.FromBounds(start, span.End));
return true;
}
}
return false;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/Core/Portable/CaseCorrection/AbstractCaseCorrectionService.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CaseCorrection
{
internal abstract partial class AbstractCaseCorrectionService : ICaseCorrectionService
{
protected abstract void AddReplacements(SemanticModel? semanticModel, SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, ConcurrentDictionary<SyntaxToken, SyntaxToken> replacements, CancellationToken cancellationToken);
public async Task<Document> CaseCorrectAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken)
{
if (!spans.Any())
{
return document;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(spans.Collapse(), cancellationToken).ConfigureAwait(false);
var newRoot = CaseCorrect(semanticModel, root, spans, document.Project.Solution.Workspace, cancellationToken);
return (root == newRoot) ? document : document.WithSyntaxRoot(newRoot);
}
public SyntaxNode CaseCorrect(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken)
=> CaseCorrect(semanticModel: null, root, spans, workspace, cancellationToken);
private SyntaxNode CaseCorrect(SemanticModel? semanticModel, SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.CaseCorrection_CaseCorrect, cancellationToken))
{
var normalizedSpanCollection = new NormalizedTextSpanCollection(spans);
var replacements = new ConcurrentDictionary<SyntaxToken, SyntaxToken>();
using (Logger.LogBlock(FunctionId.CaseCorrection_AddReplacements, cancellationToken))
{
AddReplacements(semanticModel, root, normalizedSpanCollection.ToImmutableArray(), workspace, replacements, cancellationToken);
}
using (Logger.LogBlock(FunctionId.CaseCorrection_ReplaceTokens, cancellationToken))
{
return root.ReplaceTokens(replacements.Keys, (oldToken, _) => replacements[oldToken]);
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Concurrent;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.CaseCorrection
{
internal abstract partial class AbstractCaseCorrectionService : ICaseCorrectionService
{
protected abstract void AddReplacements(SemanticModel? semanticModel, SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, ConcurrentDictionary<SyntaxToken, SyntaxToken> replacements, CancellationToken cancellationToken);
public async Task<Document> CaseCorrectAsync(Document document, ImmutableArray<TextSpan> spans, CancellationToken cancellationToken)
{
if (!spans.Any())
{
return document;
}
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
if (root is null)
{
throw new NotSupportedException(WorkspacesResources.Document_does_not_support_syntax_trees);
}
var semanticModel = await document.ReuseExistingSpeculativeModelAsync(spans.Collapse(), cancellationToken).ConfigureAwait(false);
var newRoot = CaseCorrect(semanticModel, root, spans, document.Project.Solution.Workspace, cancellationToken);
return (root == newRoot) ? document : document.WithSyntaxRoot(newRoot);
}
public SyntaxNode CaseCorrect(SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken)
=> CaseCorrect(semanticModel: null, root, spans, workspace, cancellationToken);
private SyntaxNode CaseCorrect(SemanticModel? semanticModel, SyntaxNode root, ImmutableArray<TextSpan> spans, Workspace workspace, CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.CaseCorrection_CaseCorrect, cancellationToken))
{
var normalizedSpanCollection = new NormalizedTextSpanCollection(spans);
var replacements = new ConcurrentDictionary<SyntaxToken, SyntaxToken>();
using (Logger.LogBlock(FunctionId.CaseCorrection_AddReplacements, cancellationToken))
{
AddReplacements(semanticModel, root, normalizedSpanCollection.ToImmutableArray(), workspace, replacements, cancellationToken);
}
using (Logger.LogBlock(FunctionId.CaseCorrection_ReplaceTokens, cancellationToken))
{
return root.ReplaceTokens(replacements.Keys, (oldToken, _) => replacements[oldToken]);
}
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_INoneOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_INoneOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_01()
{
string source = @"
using System;
class C
{
static void Method(bool a, int b, int c)
/*<bind>*/{
M(1, __arglist(b, (a ? b : c)));
}/*</bind>*/
static void M(int x, __arglist)
{
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(1, __argl ... ? b : c)));')
Expression:
IInvocationOperation (void C.M(System.Int32 x, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(1, __argl ... ? b : c)))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(b ... a ? b : c))')
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(b ... a ? b : c))')
Children(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c')
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)
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_02()
{
string source = @"
using System;
class C
{
static void Method(bool a, int b, int c, int d)
/*<bind>*/{
M(1, __arglist((a ? b : c), d));
}/*</bind>*/
static void M(int x, __arglist)
{
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(1, __argl ... : c), d));')
Expression:
IInvocationOperation (void C.M(System.Int32 x, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(1, __argl ... b : c), d))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(( ... b : c), d)')
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(( ... b : c), d)')
Children(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c')
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
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)
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_03()
{
string source = @"
using System;
class C
{
static void Method(bool a, int b)
/*<bind>*/{
M(1, __arglist(a, b));
}/*</bind>*/
static void M(int x, __arglist)
{
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(1, __arglist(a, b));')
Expression:
IInvocationOperation (void C.M(System.Int32 x, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(1, __arglist(a, b))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(a, b)')
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a, b)')
Children(2):
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: '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)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_04()
{
string source = @"
unsafe public class MyClass
{
public static void Main(bool a, int b, int c, int* i, int j)
/*<bind>*/{
j = i[1, (a ? b : c)];
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0196: A pointer must be indexed by only one value
// j = i[1, (a ? b : c)];
Diagnostic(ErrorCode.ERR_PtrIndexSingle, "i[1, (a ? b : c)]").WithLocation(6, 13)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32*, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'c')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'j = i[1, (a ? b : c)];')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'j = i[1, (a ? b : c)]')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
Right:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1, (a ? b : c)]')
Children(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32*, IsInvalid, IsImplicit) (Syntax: 'i')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1, (a ? b : c)]')
Children(2):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_INoneOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_01()
{
string source = @"
using System;
class C
{
static void Method(bool a, int b, int c)
/*<bind>*/{
M(1, __arglist(b, (a ? b : c)));
}/*</bind>*/
static void M(int x, __arglist)
{
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(1, __argl ... ? b : c)));')
Expression:
IInvocationOperation (void C.M(System.Int32 x, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(1, __argl ... ? b : c)))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(b ... a ? b : c))')
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(b ... a ? b : c))')
Children(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'b')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c')
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)
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_02()
{
string source = @"
using System;
class C
{
static void Method(bool a, int b, int c, int d)
/*<bind>*/{
M(1, __arglist((a ? b : c), d));
}/*</bind>*/
static void M(int x, __arglist)
{
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'c')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(1, __argl ... : c), d));')
Expression:
IInvocationOperation (void C.M(System.Int32 x, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(1, __argl ... b : c), d))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(( ... b : c), d)')
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(( ... b : c), d)')
Children(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'a ? b : c')
IParameterReferenceOperation: d (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'd')
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)
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_03()
{
string source = @"
using System;
class C
{
static void Method(bool a, int b)
/*<bind>*/{
M(1, __arglist(a, b));
}/*</bind>*/
static void M(int x, __arglist)
{
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'M(1, __arglist(a, b));')
Expression:
IInvocationOperation (void C.M(System.Int32 x, __arglist)) (OperationKind.Invocation, Type: System.Void) (Syntax: 'M(1, __arglist(a, b))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: x) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: null) (OperationKind.Argument, Type: null) (Syntax: '__arglist(a, b)')
IOperation: (OperationKind.None, Type: null) (Syntax: '__arglist(a, b)')
Children(2):
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'a')
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: '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)
Next (Regular) Block[B2]
Block[B2] - Exit
Predecessors: [B1]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void NoneOperation_Expression_04()
{
string source = @"
unsafe public class MyClass
{
public static void Main(bool a, int b, int c, int* i, int j)
/*<bind>*/{
j = i[1, (a ? b : c)];
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0196: A pointer must be indexed by only one value
// j = i[1, (a ? b : c)];
Diagnostic(ErrorCode.ERR_PtrIndexSingle, "i[1, (a ? b : c)]").WithLocation(6, 13)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'j')
Value:
IParameterReferenceOperation: j (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'j')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'i')
Value:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32*, IsInvalid) (Syntax: 'i')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '1')
Value:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Boolean, IsInvalid) (Syntax: 'a')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'b')
Value:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'b')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c')
Value:
IParameterReferenceOperation: c (OperationKind.ParameterReference, Type: System.Int32, IsInvalid) (Syntax: 'c')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'j = i[1, (a ? b : c)];')
Expression:
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid) (Syntax: 'j = i[1, (a ? b : c)]')
Left:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'j')
Right:
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'i[1, (a ? b : c)]')
Children(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32*, IsInvalid, IsImplicit) (Syntax: 'i')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'i[1, (a ? b : c)]')
Children(2):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, Constant: 1, IsInvalid, IsImplicit) (Syntax: '1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'a ? b : c')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, compilationOptions: TestOptions.UnsafeDebugDll);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Test/Semantic/Semantics/DeconstructionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
[CompilerTrait(CompilerFeature.Tuples)]
public class DeconstructionTests : CompilingTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
const string commonSource =
@"public class Pair<T1, T2>
{
T1 item1;
T2 item2;
public Pair(T1 item1, T2 item2)
{
this.item1 = item1;
this.item2 = item2;
}
public void Deconstruct(out T1 item1, out T2 item2)
{
System.Console.WriteLine($""Deconstructing {ToString()}"");
item1 = this.item1;
item2 = this.item2;
}
public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; }
}
public static class Pair
{
public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); }
}
public class Integer
{
public int state;
public override string ToString() { return state.ToString(); }
public Integer(int i) { state = i; }
public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); }
}
public class LongInteger
{
long state;
public LongInteger(long l) { state = l; }
public override string ToString() { return state.ToString(); }
}";
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodMissing()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C", "Deconstruct").WithLocation(8, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWrongParams()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a) // too few arguments
{
a = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1501: No overload for method 'Deconstruct' takes 2 arguments
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("Deconstruct", "2").WithLocation(8, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWrongParams2()
{
string source = @"
class C
{
static void Main()
{
long x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a, out int b, out int c) // too many arguments
{
a = b = c = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.Int64 y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.Int64 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'c' of 'C.Deconstruct(out int, out int, out int)'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("c", "C.Deconstruct(out int, out int, out int)").WithLocation(7, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignmentWithLeftHandSideErrors()
{
string source = @"
class C
{
static void Main()
{
long x = 1;
string y = ""hello"";
/*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
}
public void Deconstruct() { }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x.f, y.g) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (? f, ? g), IsInvalid) (Syntax: '(x.f, y.g)')
NaturalType: (? f, ? g)
Elements(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.f')
Children(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y.g')
Children(1):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'long' does not contain a definition for 'f' and no extension method 'f' accepting a first argument of type 'long' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "f").WithArguments("long", "f").WithLocation(8, 22),
// CS1061: 'string' does not contain a definition for 'g' and no extension method 'g' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "g").WithArguments("string", "g").WithLocation(8, 27),
// CS1501: No overload for method 'Deconstruct' takes 2 arguments
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("Deconstruct", "2").WithLocation(8, 32),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWithInParam()
{
string source = @"
class C
{
static void Main()
{
int x;
int y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int x, int y) { x = 1; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1615: Argument 2 may not be passed with the 'out' keyword
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "(x, y) = new C()").WithArguments("2", "out").WithLocation(8, 19),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWithRefParam()
{
string source = @"
class C
{
static void Main()
{
int x;
int y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(ref int x, out int y) { x = 1; y = 2; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1620: Argument 1 must be passed with the 'ref' keyword
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgRef, "(x, y) = new C()").WithArguments("1", "ref").WithLocation(8, 19),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructManually()
{
string source = @"
struct C
{
static void Main()
{
long x;
string y;
C c = new C();
c.Deconstruct(out x, out y); // error
/*<bind>*/(x, y) = c/*</bind>*/;
}
void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y) = c')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// c.Deconstruct(out x, out y); // error
Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "out long", "out int").WithLocation(10, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodHasOptionalParam()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, int c = 42) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void BadDeconstructShadowsBaseDeconstruct()
{
string source = @"
class D
{
public void Deconstruct(out int a, out string b) { a = 2; b = ""world""; }
}
class C : D
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, int c = 42) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(13, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodHasParams()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodHasArglist()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.Deconstruct(out int, out string, __arglist)'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("__arglist", "C.Deconstruct(out int, out string, __arglist)").WithLocation(9, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructDelegate()
{
string source = @"
delegate void D1(out int x, out int y);
class C
{
public D1 Deconstruct; // not a Deconstruct operator
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
}
public static void DeconstructMethod(out int a, out int b) { a = 1; b = 2; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = ne ... uctMethod }')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C() { D ... uctMethod }')
Arguments(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ Deconstru ... uctMethod }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: D1, IsInvalid) (Syntax: 'Deconstruct ... tructMethod')
Left:
IFieldReferenceOperation: D1 C.Deconstruct (OperationKind.FieldReference, Type: D1, IsInvalid) (Syntax: 'Deconstruct')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'Deconstruct')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: D1, IsInvalid, IsImplicit) (Syntax: 'DeconstructMethod')
Target:
IMethodReferenceOperation: void C.DeconstructMethod(out System.Int32 a, out System.Int32 b) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'DeconstructMethod')
Instance Receiver:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C() { Deconstruct = DeconstructMethod }").WithArguments("C", "2").WithLocation(11, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructDelegate2()
{
string source = @"
delegate void D1(out int x, out int y);
class C
{
public D1 Deconstruct;
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
}
public static void DeconstructMethod(out int a, out int b) { a = 1; b = 2; }
public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y), IsInvalid) (Syntax: '(x, y) = ne ... uctMethod }')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C() { D ... uctMethod }')
Arguments(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ Deconstru ... uctMethod }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Deconstruct ... tructMethod')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Deconstruct')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Deconstruct')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C')
Right:
IOperation: (OperationKind.None, Type: null) (Syntax: 'DeconstructMethod')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'DeconstructMethod')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0102: The type 'C' already contains a definition for 'Deconstruct'
// public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Deconstruct").WithArguments("C", "Deconstruct").WithLocation(16, 17),
// CS1913: Member 'Deconstruct' cannot be initialized. It is not a field or property.
// /*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "Deconstruct").WithArguments("Deconstruct").WithLocation(11, 38),
// CS0649: Field 'C.Deconstruct' is never assigned to, and will always have its default value null
// public D1 Deconstruct;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Deconstruct").WithArguments("C.Deconstruct", "null").WithLocation(6, 15)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructEvent()
{
string source = @"
delegate void D1(out int x, out int y);
class C
{
public event D1 Deconstruct; // not a Deconstruct operator
static void Main()
{
long x;
int y;
C c = new C();
c.Deconstruct += DeconstructMethod;
/*<bind>*/(x, y) = c/*</bind>*/;
}
public static void DeconstructMethod(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = c')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = c/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "c").WithArguments("C", "2").WithLocation(14, 28),
// CS0067: The event 'C.Deconstruct' is never used
// public event D1 Deconstruct; // not a Deconstruct operator
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Deconstruct").WithArguments("C.Deconstruct").WithLocation(6, 21)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConversionErrors()
{
string source = @"
class C
{
static void Main()
{
byte x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Byte x, System.String y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (System.Byte x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("int", "byte").WithLocation(8, 20),
// CS0029: Cannot implicitly convert type 'int' to 'string'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "y").WithArguments("int", "string").WithLocation(8, 23)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void ExpressionType()
{
string source = @"
class C
{
static void Main()
{
int x, y;
var type = ((x, y) = new C()).GetType();
System.Console.Write(type.ToString());
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "System.ValueTuple`2[System.Int32,System.Int32]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ExpressionType_IOperation()
{
string source = @"
class C
{
static void Main()
{
int x, y;
var type = (/*<bind>*/(x, y) = new C()/*</bind>*/).GetType();
System.Console.Write(type.ToString());
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LambdaStillNotValidStatement()
{
string source = @"
class C
{
static void Main()
{
(a) => a;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (a) => a;
Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LambdaWithBodyStillNotValidStatement()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(a, b) => { }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(a, b) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// /*<bind>*/(a, b) => { }/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void CastButNotCast()
{
// int and string must be types, so (int, string) must be type and ((int, string)) a cast, but then .String() cannot follow a cast...
string source = @"
class C
{
static void Main()
{
/*<bind>*/((int, string)).ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvocationOperation (virtual System.String (System.Int32, System.String).ToString()) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: '((int, stri ... .ToString()')
Instance Receiver:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.String), IsInvalid) (Syntax: '(int, string)')
NaturalType: (System.Int32, System.String)
Elements(2):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'int')
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'string')
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'int'
// /*<bind>*/((int, string)).ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 21),
// CS1525: Invalid expression term 'string'
// /*<bind>*/((int, string)).ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(6, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningMethod2()
{
string source = @"
class C
{
static int i;
static void Main()
{
(M(), M()) = new C();
System.Console.Write(i);
}
static ref int M()
{
System.Console.Write(""M "");
return ref i;
}
void Deconstruct(out int i, out int j)
{
i = 42;
j = 43;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "M M 43");
comp.VerifyDiagnostics(
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningMethod2_IOperation()
{
string source = @"
class C
{
static int i;
static void Main()
{
/*<bind>*/(M(), M()) = new C()/*</bind>*/;
System.Console.Write(i);
}
static ref int M()
{
System.Console.Write(""M "");
return ref i;
}
void Deconstruct(out int i, out int j)
{
i = 42;
j = 43;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32)) (Syntax: '(M(), M()) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(M(), M())')
NaturalType: (System.Int32, System.Int32)
Elements(2):
IInvocationOperation (ref System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
IInvocationOperation (ref System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UninitializedRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = x/*</bind>*/;
}
}
static class D
{
public static void Deconstruct(this int input, out int output, out int output2) { output = input; output2 = input; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(x, x) = x')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0165: Use of unassigned local variable 'x'
// /*<bind>*/(x, x) = x/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NullRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(x, x) = null')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/(x, x) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ErrorRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = undeclared/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(x, x) = undeclared')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'undeclared')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'undeclared' does not exist in the current context
// /*<bind>*/(x, x) = undeclared/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "undeclared").WithArguments("undeclared").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VoidRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = M()/*</bind>*/;
}
static void M() { }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, x) = M()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
IInvocationOperation (void C.M()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'void' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'void' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x, x) = M()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M()").WithArguments("void", "Deconstruct").WithLocation(7, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'void', with 2 out parameters and a void return type.
// /*<bind>*/(x, x) = M()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "M()").WithArguments("void", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssigningTupleWithNoConversion()
{
string source = @"
class C
{
static void Main()
{
byte x;
string y;
/*<bind>*/(x, y) = (1, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Byte x, System.String y), IsInvalid) (Syntax: '(x, y) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Byte x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Byte x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Byte) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.String), IsInvalid, IsImplicit) (Syntax: '(1, 2)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'int' to 'string'
// /*<bind>*/(x, y) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(9, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NotAssignable()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(1, P) = (1, 2)/*</bind>*/;
}
static int P { get { return 1; } }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32 P), IsInvalid) (Syntax: '(1, P) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32 P), IsInvalid) (Syntax: '(1, P)')
NaturalType: (System.Int32, System.Int32 P)
Elements(2):
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'P')
Children(1):
IPropertyReferenceOperation: System.Int32 C.P { get; } (Static) (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'P')
Instance Receiver:
null
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0131: The left-hand side of an assignment must be a variable, property or indexer
// /*<bind>*/(1, P) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(6, 20),
// CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only
// /*<bind>*/(1, P) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(6, 23)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TupleWithUseSiteError()
{
string source = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
}
}
}
class C
{
static void Main()
{
int x;
int y;
(x, y) = (1, 2);
System.Console.WriteLine($""{x} {y}"");
}
}
";
var comp = CreateCompilation(source, assemblyName: "comp", options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TupleWithUseSiteError_IOperation()
{
string source = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public T1 Item1;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
}
}
}
class C
{
static void Main()
{
int x;
int y;
/*<bind>*/(x, y) = (1, 2)/*</bind>*/;
System.Console.WriteLine($""{x} {y}"");
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignUsingAmbiguousDeconstruction()
{
string source = @"
class Base
{
public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
public void Deconstruct(out long a, out long b) { a = 1; b = 2; }
}
class C : Base
{
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(12,28): error CS0121: The call is ambiguous between the following methods or properties: 'Base.Deconstruct(out int, out int)' and 'Base.Deconstruct(out long, out long)'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigCall, "new C()").WithArguments("Base.Deconstruct(out int, out int)", "Base.Deconstruct(out long, out long)").WithLocation(12, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructIsDynamicField()
{
string source = @"
class C
{
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public dynamic Deconstruct = null;
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructIsField()
{
string source = @"
class C
{
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public object Deconstruct = null;
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1955: Non-invocable member 'C.Deconstruct' cannot be used like a method.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "new C()").WithArguments("C.Deconstruct").WithLocation(7, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void CannotDeconstructRefTuple22()
{
string template = @"
using System;
class C
{
static void Main()
{
int VARIABLES; // int x1, x2, ...
(VARIABLES) = CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)));
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) =>
new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
}
";
var tuple = String.Join(", ", Enumerable.Range(1, 22).Select(n => n.ToString()));
var variables = String.Join(", ", Enumerable.Range(1, 22).Select(n => $"x{n}"));
var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple);
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,113): error CS1501: No overload for method 'Deconstruct' takes 22 arguments
// (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22) = CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)));
Diagnostic(ErrorCode.ERR_BadArgCount, "CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)))").WithArguments("Deconstruct", "22").WithLocation(8, 113),
// (8,113): error CS8129: No Deconstruct instance or extension method was found for type 'Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, int, int, int, Tuple<int>>>>', with 22 out parameters.
// (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22) = CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)))").WithArguments("System.Tuple<int, int, int, int, int, int, int, System.Tuple<int, int, int, int, int, int, int, System.Tuple<int, int, int, int, int, int, int, System.Tuple<int>>>>", "22").WithLocation(8, 113)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructUsingDynamicMethod()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
dynamic c = new C();
/*<bind>*/(x, y) = c/*</bind>*/;
}
public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = c')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: dynamic, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8133: Cannot deconstruct dynamic objects.
// /*<bind>*/(x, y) = c/*</bind>*/;
Diagnostic(ErrorCode.ERR_CannotDeconstructDynamic, "c").WithLocation(10, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodInaccessible()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
/*<bind>*/(x, y) = new C1()/*</bind>*/;
}
}
class C1
{
protected void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C1()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0122: 'C1.Deconstruct(out int, out string)' is inaccessible due to its protection level
// /*<bind>*/(x, y) = new C1()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadAccess, "new C1()").WithArguments("C1.Deconstruct(out int, out string)").WithLocation(9, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C1()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DeconstructHasUseSiteError()
{
string libMissingSource = @"public class Missing { }";
string libSource = @"
public class C
{
public void Deconstruct(out Missing a, out Missing b) { a = new Missing(); b = new Missing(); }
}
";
string source = @"
class C1
{
static void Main()
{
object x, y;
(x, y) = new C();
}
}
";
var libMissingComp = CreateCompilation(new string[] { libMissingSource }, assemblyName: "libMissingComp").VerifyDiagnostics();
var libMissingRef = libMissingComp.EmitToImageReference();
var libComp = CreateCompilation(new string[] { libSource }, references: new[] { libMissingRef }, parseOptions: TestOptions.Regular).VerifyDiagnostics();
var libRef = libComp.EmitToImageReference();
var comp = CreateCompilation(new string[] { source }, references: new[] { libRef });
comp.VerifyDiagnostics(
// (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'libMissingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C()").WithArguments("Missing", "libMissingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (7,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 18)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void StaticDeconstruct()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public static void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0176: Member 'C.Deconstruct(out int, out string)' cannot be accessed with an instance reference; qualify it with a type name instead
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void AssignmentTypeIsValueTuple()
{
string source = @"
class C
{
public static void Main()
{
long x; string y;
var z1 = ((x, y) = new C()).ToString();
var z2 = ((x, y) = new C());
var z3 = (x, y) = new C();
System.Console.Write($""{z1} {z2.ToString()} {z3.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, hello) (1, hello) (1, hello)");
comp.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignmentTypeIsValueTuple_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x; string y;
var z1 = ((x, y) = new C()).ToString();
var z2 = (/*<bind>*/(x, y) = new C()/*</bind>*/);
var z3 = (x, y) = new C();
System.Console.Write($""{z1} {z2.ToString()} {z3.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void NestedAssignmentTypeIsValueTuple()
{
string source = @"
class C
{
public static void Main()
{
long x1; string x2; int x3;
var y = ((x1, x2), x3) = (new C(), 3);
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "((1, hello), 3)");
comp.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NestedAssignmentTypeIsValueTuple_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x1; string x2; int x3;
var y = /*<bind>*/((x1, x2), x3) = (new C(), 3)/*</bind>*/;
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ((System.Int64 x1, System.String x2), System.Int32 x3)) (Syntax: '((x1, x2), ... new C(), 3)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((System.Int64 x1, System.String x2), System.Int32 x3)) (Syntax: '((x1, x2), x3)')
NaturalType: ((System.Int64 x1, System.String x2), System.Int32 x3)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x1, System.String x2)) (Syntax: '(x1, x2)')
NaturalType: (System.Int64 x1, System.String x2)
Elements(2):
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x1')
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.String) (Syntax: 'x2')
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x3')
Right:
ITupleOperation (OperationKind.Tuple, Type: (C, System.Int32)) (Syntax: '(new C(), 3)')
NaturalType: (C, System.Int32)
Elements(2):
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void AssignmentReturnsLongValueTuple()
{
string source = @"
class C
{
public static void Main()
{
long x;
var y = (x, x, x, x, x, x, x, x, x) = new C();
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int x1, out int x2, out int x3, out int x4, out int x5, out int x6, out int x7, out int x8, out int x9)
{
x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = 1;
x9 = 9;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 1, 1, 1, 1, 1, 1, 1, 9)");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var y = nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First();
Assert.Equal("y = (x, x, x, x, x, x, x, x, x) = new C()", y.ToFullString());
Assert.Equal("(System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64) y",
model.GetDeclaredSymbol(y).ToTestDisplayString());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignmentReturnsLongValueTuple_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x;
var /*<bind>*/y = (x, x, x, x, x, x, x, x, x) = new C()/*</bind>*/;
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int x1, out int x2, out int x3, out int x4, out int x5, out int x6, out int x7, out int x8, out int x9)
{
x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = 1;
x9 = 9;
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64) y) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y = (x, x, ... ) = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (x, x, x, ... ) = new C()')
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64)) (Syntax: '(x, x, x, x ... ) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64)) (Syntax: '(x, x, x, x ... x, x, x, x)')
NaturalType: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64)
Elements(9):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DeconstructWithoutValueTupleLibrary()
{
string source = @"
class C
{
public static void Main()
{
long x;
var y = (x, x) = new C();
System.Console.Write(y.ToString());
}
public void Deconstruct(out int x1, out int x2)
{
x1 = x2 = 1;
}
}
";
var comp = CreateCompilationWithMscorlib40(source);
comp.VerifyDiagnostics(
// (7,17): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// var y = (x, x) = new C();
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(x, x)").WithArguments("System.ValueTuple`2").WithLocation(7, 17)
);
}
[Fact]
public void ChainedAssignment()
{
string source = @"
class C
{
public static void Main()
{
long x1, x2;
var y = (x1, x1) = (x2, x2) = new C();
System.Console.Write($""{y.ToString()} {x1} {x2}"");
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(1, 1) 1 1");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ChainedAssignment_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x1, x2;
var y = /*<bind>*/(x1, x1) = (x2, x2) = new C()/*</bind>*/;
System.Console.Write($""{y.ToString()} {x1} {x2}"");
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64, System.Int64)) (Syntax: '(x1, x1) = ... ) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64, System.Int64)) (Syntax: '(x1, x1)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x1')
Right:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64, System.Int64)) (Syntax: '(x2, x2) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64, System.Int64)) (Syntax: '(x2, x2)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x2')
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x2')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NestedTypelessTupleAssignment2()
{
string source = @"
class C
{
static void Main()
{
int x, y, z; // int cannot be null
/*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
System.Console.WriteLine(""nothing"" + x + y + z);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, (System.Int32 y, System.Int32 z)), IsInvalid) (Syntax: '(x, (y, z)) ... ull, null))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, (System.Int32 y, System.Int32 z))) (Syntax: '(x, (y, z))')
NaturalType: (System.Int32 x, (System.Int32 y, System.Int32 z))
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 z)) (Syntax: '(y, z)')
NaturalType: (System.Int32 y, System.Int32 z)
Elements(2):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, (System.Int32, System.Int32)), IsInvalid, IsImplicit) (Syntax: '(null, (null, null))')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: null, IsInvalid) (Syntax: '(null, (null, null))')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ITupleOperation (OperationKind.Tuple, Type: null, IsInvalid) (Syntax: '(null, null)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// /*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 34),
// CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// /*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 41),
// CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// /*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 47)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TupleWithWrongCardinality()
{
string source = @"
class C
{
static void Main()
{
int x, y, z;
/*<bind>*/(x, y, z) = MakePair()/*</bind>*/;
}
public static (int, int) MakePair()
{
return (42, 42);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y, z) = MakePair()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y, System.Int32 z), IsInvalid) (Syntax: '(x, y, z)')
NaturalType: (System.Int32 x, System.Int32 y, System.Int32 z)
Elements(3):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
Right:
IInvocationOperation ((System.Int32, System.Int32) C.MakePair()) (OperationKind.Invocation, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'MakePair()')
Instance Receiver:
null
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// /*<bind>*/(x, y, z) = MakePair()/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = MakePair()").WithArguments("2", "3").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NestedTupleWithWrongCardinality()
{
string source = @"
class C
{
static void Main()
{
int x, y, z, w;
/*<bind>*/(x, (y, z, w)) = Pair.Create(42, (43, 44))/*</bind>*/;
}
}
" + commonSource;
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, (y, z, ... , (43, 44))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, (System.Int32 y, System.Int32 z, System.Int32 w)), IsInvalid) (Syntax: '(x, (y, z, w))')
NaturalType: (System.Int32 x, (System.Int32 y, System.Int32 z, System.Int32 w))
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 z, System.Int32 w), IsInvalid) (Syntax: '(y, z, w)')
NaturalType: (System.Int32 y, System.Int32 z, System.Int32 w)
Elements(3):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
ILocalReferenceOperation: w (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'w')
Right:
IInvocationOperation (Pair<System.Int32, (System.Int32, System.Int32)> Pair.Create<System.Int32, (System.Int32, System.Int32)>(System.Int32 item1, (System.Int32, System.Int32) item2)) (OperationKind.Invocation, Type: Pair<System.Int32, (System.Int32, System.Int32)>, IsInvalid) (Syntax: 'Pair.Create ... , (43, 44))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item1) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '42')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item2) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '(43, 44)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(43, 44)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43, IsInvalid) (Syntax: '43')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 44, IsInvalid) (Syntax: '44')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// /*<bind>*/(x, (y, z, w)) = Pair.Create(42, (43, 44))/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, (y, z, w)) = Pair.Create(42, (43, 44))").WithArguments("2", "3").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructionTooFewElements()
{
string source = @"
class C
{
static void Main()
{
for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
}
}
" + commonSource;
string expectedOperationTree = @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '(var(x, y)) ... reate(1, 2)')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x, y)')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y')
Children(0)
Right:
IInvocationOperation (Pair<System.Int32, System.Int32> Pair.Create<System.Int32, System.Int32>(System.Int32 item1, System.Int32 item2)) (OperationKind.Invocation, Type: Pair<System.Int32, System.Int32>) (Syntax: 'Pair.Create(1, 2)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item1) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item2) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'var' does not exist in the current context
// for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 25),
// CS0103: The name 'x' does not exist in the current context
// for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 29),
// CS0103: The name 'y' does not exist in the current context
// for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DeconstructionDeclarationInCSharp6()
{
string source = @"
class C
{
static void Main()
{
var (x1, x2) = Pair.Create(1, 2);
(int x3, int x4) = Pair.Create(1, 2);
foreach ((int x5, var (x6, x7)) in new[] { Pair.Create(1, Pair.Create(2, 3)) }) { }
for ((int x8, var (x9, x10)) = Pair.Create(1, Pair.Create(2, 3)); ; ) { }
}
}
" + commonSource;
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6);
comp.VerifyDiagnostics(
// (6,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (x1, x2) = Pair.Create(1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x1, x2)").WithArguments("tuples", "7.0").WithLocation(6, 13),
// (7,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// (int x3, int x4) = Pair.Create(1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int x3, int x4)").WithArguments("tuples", "7.0").WithLocation(7, 9),
// (8,18): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// foreach ((int x5, var (x6, x7)) in new[] { Pair.Create(1, Pair.Create(2, 3)) }) { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int x5, var (x6, x7))").WithArguments("tuples", "7.0").WithLocation(8, 18),
// (9,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// for ((int x8, var (x9, x10)) = Pair.Create(1, Pair.Create(2, 3)); ; ) { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int x8, var (x9, x10))").WithArguments("tuples", "7.0").WithLocation(9, 14)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclareLocalTwice()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x1) = (1, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'var (x1, x1) = (1, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'var (x1, x1)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(x1, x1)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0128: A local variable or function named 'x1' is already defined in this scope
// /*<bind>*/var (x1, x1) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(6, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclareLocalTwice2()
{
string source = @"
class C
{
static void Main()
{
string x1 = null;
/*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
System.Console.WriteLine(x1);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0128: A local variable or function named 'x1' is already defined in this scope
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 24)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VarMethodMissing()
{
string source = @"
class C
{
static void Main()
{
int x1 = 1;
int x2 = 1;
/*<bind>*/var(x1, x2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x1, x2)')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'var' does not exist in the current context
// /*<bind>*/var(x1, x2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UseBeforeDeclared()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
}
static (int, int) M(int a) { return (1, 2); }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(int x1, int x2) = M(x1)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IInvocationOperation ((System.Int32, System.Int32) C.M(System.Int32 a)) (OperationKind.Invocation, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'M(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0165: Use of unassigned local variable 'x1'
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(6, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclareWithVoidType()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
}
static void M(int a) { }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(int x1, int x2) = M(x1)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IInvocationOperation (void C.M(System.Int32 a)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'void' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'void' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M(x1)").WithArguments("void", "Deconstruct").WithLocation(6, 38),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'void', with 2 out parameters and a void return type.
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "M(x1)").WithArguments("void", "2").WithLocation(6, 38),
// CS0165: Use of unassigned local variable 'x1'
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(6, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UseBeforeDeclared2()
{
string source = @"
class C
{
static void Main()
{
System.Console.WriteLine(x1);
/*<bind>*/(int x1, int x2) = (1, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, in ... 2) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x1' before it is declared
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 34)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NullAssignmentInDeclaration()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(int x1, int x2) = null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(int x1, int x2) = null')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/(int x1, int x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NullAssignmentInVarDeclaration()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: 'var (x1, x2) = null')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/var (x1, x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(6, 34),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// /*<bind>*/var (x1, x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 24),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/var (x1, x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypelessDeclaration()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (1, null)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: 'var (x1, x2) = (1, null)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(1, null)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// /*<bind>*/var (x1, x2) = (1, null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 24),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/var (x1, x2) = (1, null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithMultipleAmbiguousVars()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, (byte x2, var x3), var x4) = (null, (2, null), null)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(string x1, ... ull), null)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, (System.Byte x2, var x3), var x4), IsInvalid) (Syntax: '(string x1, ... 3), var x4)')
NaturalType: (System.String x1, (System.Byte x2, var x3), var x4)
Elements(3):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String) (Syntax: 'x1')
ITupleOperation (OperationKind.Tuple, Type: (System.Byte x2, var x3), IsInvalid) (Syntax: '(byte x2, var x3)')
NaturalType: (System.Byte x2, var x3)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Byte) (Syntax: 'byte x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Byte) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x4')
ILocalReferenceOperation: x4 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x4')
Right:
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(null, (2, null), null)')
NaturalType: null
Elements(3):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(2, null)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x3'.
// /*<bind>*/(string x1, (byte x2, var x3), var x4) = (null, (2, null), null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x3").WithArguments("x3").WithLocation(6, 45),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x4'.
// /*<bind>*/(string x1, (byte x2, var x3), var x4) = (null, (2, null), null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x4").WithArguments("x4").WithLocation(6, 54)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyLeftNestings()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/((string x1, byte x2, var x3), int x4) = (null, 4)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '((string x1 ... = (null, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((System.String x1, System.Byte x2, var x3), System.Int32 x4), IsInvalid) (Syntax: '((string x1 ... 3), int x4)')
NaturalType: ((System.String x1, System.Byte x2, var x3), System.Int32 x4)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, System.Byte x2, var x3), IsInvalid) (Syntax: '(string x1, ... x2, var x3)')
NaturalType: (System.String x1, System.Byte x2, var x3)
Elements(3):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Byte) (Syntax: 'byte x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Byte) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x4')
ILocalReferenceOperation: x4 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x4')
Right:
ITupleOperation (OperationKind.Tuple, Type: null, IsInvalid) (Syntax: '(null, 4)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/((string x1, byte x2, var x3), int x4) = (null, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(6, 61),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x3'.
// /*<bind>*/((string x1, byte x2, var x3), int x4) = (null, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x3").WithArguments("x3").WithLocation(6, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyRightNestings()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, var x2) = (null, (null, 2))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(string x1, ... (null, 2))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, var x2), IsInvalid) (Syntax: '(string x1, var x2)')
NaturalType: (System.String x1, var x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(null, (null, 2))')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(null, 2)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/(string x1, var x2) = (null, (null, 2))/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyLeftVariables()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, var x2, int x3) = (null, ""hello"")/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(string x1, ... l, ""hello"")')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, System.String x2, System.Int32 x3), IsInvalid) (Syntax: '(string x1, ... x2, int x3)')
NaturalType: (System.String x1, System.String x2, System.Int32 x3)
Elements(3):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'var x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.String, System.String), IsInvalid) (Syntax: '(null, ""hello"")')
NaturalType: null
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"", IsInvalid) (Syntax: '""hello""')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// /*<bind>*/(string x1, var x2, int x3) = (null, "hello")/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, @"(string x1, var x2, int x3) = (null, ""hello"")").WithArguments("2", "3").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyRightElements()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, var y1) = (null, ""hello"", 3)/*</bind>*/;
(string x2, var y2) = (null, ""hello"", null);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(string x1, ... ""hello"", 3)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, System.String y1), IsInvalid) (Syntax: '(string x1, var y1)')
NaturalType: (System.String x1, System.String y1)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'var y1')
ILocalReferenceOperation: y1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'y1')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.String, System.String, System.Int32), IsInvalid) (Syntax: '(null, ""hello"", 3)')
NaturalType: null
Elements(3):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"", IsInvalid) (Syntax: '""hello""')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '3' elements into '2' variables.
// /*<bind>*/(string x1, var y1) = (null, "hello", 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, @"(string x1, var y1) = (null, ""hello"", 3)").WithArguments("3", "2").WithLocation(6, 19),
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// (string x2, var y2) = (null, "hello", null);
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(7, 47),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'.
// (string x2, var y2) = (null, "hello", null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationVarFormWithActualVarType()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
}
}
class var { }
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (var, var), IsInvalid, IsImplicit) (Syntax: '(1, 2)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, x2)").WithLocation(6, 23),
// CS0029: Cannot implicitly convert type 'int' to 'var'
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "var").WithLocation(6, 35),
// CS0029: Cannot implicitly convert type 'int' to 'var'
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "var").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationVarFormWithAliasedVarType()
{
string source = @"
using var = D;
class C
{
static void Main()
{
/*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
}
}
class D
{
public override string ToString() { return ""var""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (D x3, D x4), IsInvalid) (Syntax: 'var (x3, x4) = (3, 4)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (D x3, D x4), IsInvalid) (Syntax: 'var (x3, x4)')
ITupleOperation (OperationKind.Tuple, Type: (D x3, D x4), IsInvalid) (Syntax: '(x3, x4)')
NaturalType: (D x3, D x4)
Elements(2):
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: D, IsInvalid) (Syntax: 'x3')
ILocalReferenceOperation: x4 (IsDeclaration: True) (OperationKind.LocalReference, Type: D, IsInvalid) (Syntax: 'x4')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (D, D), IsInvalid, IsImplicit) (Syntax: '(3, 4)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsInvalid) (Syntax: '4')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// /*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x3, x4)").WithLocation(7, 23),
// CS0029: Cannot implicitly convert type 'int' to 'D'
// /*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "3").WithArguments("int", "D").WithLocation(7, 35),
// CS0029: Cannot implicitly convert type 'int' to 'D'
// /*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "4").WithArguments("int", "D").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithWrongCardinality()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(var (x1, x ... = (1, 2, 3)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((var x1, var x2), System.Int32 x3), IsInvalid) (Syntax: '(var (x1, x2), var x3)')
NaturalType: ((var x1, var x2), System.Int32 x3)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32, System.Int32), IsInvalid) (Syntax: '(1, 2, 3)')
NaturalType: (System.Int32, System.Int32, System.Int32)
Elements(3):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '3' elements into '2' variables.
// /*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(var (x1, x2), var x3) = (1, 2, 3)").WithArguments("3", "2").WithLocation(6, 19),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// /*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 25),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 29)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithCircularity1()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, var x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, x1)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x1, var x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, var x2)) (Syntax: '(x1, x2)')
NaturalType: (System.Int32 x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, var), IsInvalid, IsImplicit) (Syntax: '(1, x1)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, var x1), IsInvalid) (Syntax: '(1, x1)')
NaturalType: (System.Int32, var x1)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x1' before it is declared
// /*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithCircularity2()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (var x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2) = (x2, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, System.Int32 x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, System.Int32 x2)) (Syntax: '(x1, x2)')
NaturalType: (var x1, System.Int32 x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (var, System.Int32), IsInvalid, IsImplicit) (Syntax: '(x2, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (var x2, System.Int32), IsInvalid) (Syntax: '(x2, 2)')
NaturalType: (var x2, System.Int32)
Elements(2):
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x2' before it is declared
// /*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(6, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningVarInvocation()
{
string source = @"
class C
{
static int i;
static void Main()
{
int x = 0, y = 0;
/*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
System.Console.WriteLine(i);
}
static ref int var(int a, int b) { return ref i; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: 'var (x, y) = 42')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x, var y), IsInvalid) (Syntax: 'var (x, y)')
ITupleOperation (OperationKind.Tuple, Type: (var x, var y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (var x, var y)
Elements(2):
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0128: A local variable or function named 'x' is already defined in this scope
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(9, 24),
// CS0128: A local variable or function named 'y' is already defined in this scope
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(9, 27),
// CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("int", "Deconstruct").WithLocation(9, 32),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'int', with 2 out parameters and a void return type.
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "42").WithArguments("int", "2").WithLocation(9, 32),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'.
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(9, 24),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'.
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(9, 27),
// CS0219: The variable 'x' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13),
// CS0219: The variable 'y' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(8, 20)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/12468"), CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")]
public void RefReturningVarInvocation2()
{
string source = @"
class C
{
static int i = 0;
static void Main()
{
int x = 0, y = 0;
@var(x, y) = 42; // parsed as invocation
System.Console.Write(i + "" "");
(var(x, y)) = 43; // parsed as invocation
System.Console.Write(i + "" "");
(var(x, y) = 44); // parsed as invocation
System.Console.Write(i);
}
static ref int var(int a, int b) { return ref i; }
}
";
// The correct expectation is for the code to compile and execute
//var comp = CompileAndVerify(source, expectedOutput: "42 43 44");
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,9): error CS8134: Deconstruction must contain at least two variables.
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_DeconstructTooFewElements, "(var(x, y)) = 43").WithLocation(11, 9),
// (13,20): error CS1026: ) expected
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_CloseParenExpected, "=").WithLocation(13, 20),
// (13,24): error CS1002: ; expected
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(13, 24),
// (13,24): error CS1513: } expected
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(13, 24),
// (9,14): error CS0128: A local variable named 'x' is already defined in this scope
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(9, 14),
// (9,9): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(9, 9),
// (9,14): error CS8136: Deconstruction `var (...)` form disallows a specific type for 'var'.
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "x").WithLocation(9, 14),
// (9,17): error CS0128: A local variable named 'y' is already defined in this scope
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(9, 17),
// (9,9): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(9, 9),
// (9,17): error CS8136: Deconstruction `var (...)` form disallows a specific type for 'var'.
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "y").WithLocation(9, 17),
// (9,22): error CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("int", "Deconstruct").WithLocation(9, 22),
// (9,22): error CS8129: No Deconstruct instance or extension method was found for type 'int', with 2 out parameters.
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "42").WithArguments("int", "2").WithLocation(9, 22),
// (11,14): error CS0128: A local variable named 'x' is already defined in this scope
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(11, 14),
// (11,17): error CS0128: A local variable named 'y' is already defined in this scope
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(11, 17),
// (11,23): error CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "43").WithArguments("int", "Deconstruct").WithLocation(11, 23),
// (11,23): error CS8129: No Deconstruct instance or extension method was found for type 'int', with 1 out parameters.
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "43").WithArguments("int", "1").WithLocation(11, 23),
// (13,14): error CS0128: A local variable named 'x' is already defined in this scope
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(13, 14),
// (13,17): error CS0128: A local variable named 'y' is already defined in this scope
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(13, 17),
// (13,22): error CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "44").WithArguments("int", "Deconstruct").WithLocation(13, 22),
// (13,22): error CS8129: No Deconstruct instance or extension method was found for type 'int', with 1 out parameters.
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "44").WithArguments("int", "1").WithLocation(13, 22),
// (8,13): warning CS0219: The variable 'x' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13),
// (8,20): warning CS0219: The variable 'y' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(8, 20)
);
}
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningInvocation()
{
string source = @"
class C
{
static int i;
static void Main()
{
int x = 0, y = 0;
M(x, y) = 42;
System.Console.WriteLine(i);
}
static ref int M(int a, int b) { return ref i; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "42");
comp.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithTypeInsideVarForm()
{
string source = @"
class C
{
static void Main()
{
var(int x1, x2) = (1, 2);
var(var x3, x4) = (1, 2);
/*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'var(x5, var ... (1, (2, 3))')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x5, var(x6, x7))')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x5')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x6, x7)')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x6')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x7')
Children(0)
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'int'
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 13),
// CS1003: Syntax error, ',' expected
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 17),
// CS1003: Syntax error, ',' expected
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(7, 17),
// CS8199: The syntax 'var (...)' as an lvalue is reserved.
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(int x1, x2)").WithLocation(6, 9),
// CS0103: The name 'var' does not exist in the current context
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9),
// CS0103: The name 'x1' does not exist in the current context
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 17),
// CS0103: The name 'x2' does not exist in the current context
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 21),
// CS8199: The syntax 'var (...)' as an lvalue is reserved.
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(var x3, x4)").WithLocation(7, 9),
// CS0103: The name 'var' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 9),
// CS0103: The name 'var' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 13),
// CS0103: The name 'x3' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(7, 17),
// CS0103: The name 'x4' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(7, 21),
// CS8199: The syntax 'var (...)' as an lvalue is reserved.
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x5, var(x6, x7))").WithLocation(8, 19),
// CS0103: The name 'var' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19),
// CS0103: The name 'x5' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(8, 23),
// CS0103: The name 'var' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 27),
// CS0103: The name 'x6' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(8, 31),
// CS0103: The name 'x7' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(8, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForWithCircularity1()
{
string source = @"
class C
{
static void Main()
{
for (/*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/; ;) { }
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, var x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, x1)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x1, var x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, var x2)) (Syntax: '(x1, x2)')
NaturalType: (System.Int32 x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, var), IsInvalid, IsImplicit) (Syntax: '(1, x1)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, var x1), IsInvalid) (Syntax: '(1, x1)')
NaturalType: (System.Int32, var x1)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x1' before it is declared
// for (/*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 43)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForWithCircularity2()
{
string source = @"
class C
{
static void Main()
{
for (/*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/; ;) { }
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (var x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2) = (x2, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, System.Int32 x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, System.Int32 x2)) (Syntax: '(x1, x2)')
NaturalType: (var x1, System.Int32 x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (var, System.Int32), IsInvalid, IsImplicit) (Syntax: '(x2, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (var x2, System.Int32), IsInvalid) (Syntax: '(x2, 2)')
NaturalType: (var x2, System.Int32)
Elements(2):
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x2' before it is declared
// for (/*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(6, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachNameConflict()
{
string source = @"
class C
{
static void Main()
{
int x1 = 1;
/*<bind>*/foreach ((int x1, int x2) in M()) { }/*</bind>*/
System.Console.Write(x1);
}
static (int, int)[] M() { return new[] { (1, 2) }; }
}
";
string expectedOperationTree = @"
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'foreach ((i ... in M()) { }')
Locals: Local_1: System.Int32 x1
Local_2: System.Int32 x2
LoopControlVariable:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'M()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ((System.Int32, System.Int32)[] C.M()) (OperationKind.Invocation, Type: (System.Int32, System.Int32)[]) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
NextVariables(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// /*<bind>*/foreach ((int x1, int x2) in M()) { }/*</bind>*/
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(7, 33)
};
VerifyOperationTreeAndDiagnosticsForTest<ForEachVariableStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachNameConflict2()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/foreach ((int x1, int x2) in M(out int x1)) { }/*</bind>*/
}
static (int, int)[] M(out int a) { a = 1; return new[] { (1, 2) }; }
}
";
string expectedOperationTree = @"
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'foreach ((i ... nt x1)) { }')
Locals: Local_1: System.Int32 x1
Local_2: System.Int32 x2
LoopControlVariable:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'M(out int x1)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ((System.Int32, System.Int32)[] C.M(out System.Int32 a)) (OperationKind.Invocation, Type: (System.Int32, System.Int32)[]) (Syntax: 'M(out int x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
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)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
NextVariables(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// /*<bind>*/foreach ((int x1, int x2) in M(out int x1)) { }/*</bind>*/
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(6, 33)
};
VerifyOperationTreeAndDiagnosticsForTest<ForEachVariableStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void ForEachNameConflict3()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, int x2) in M())
{
int x1 = 1;
System.Console.Write(x1);
}
}
static (int, int)[] M() { return new[] { (1, 2) }; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,17): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x1 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(8, 17)
);
}
[Fact]
public void ForEachUseBeforeDeclared()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, int x2) in M(x1)) { }
}
static (int, int)[] M(int a) { return new[] { (1, 2) }; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,40): error CS0103: The name 'x1' does not exist in the current context
// foreach ((int x1, int x2) in M(x1))
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 40)
);
}
[Fact]
public void ForEachUseOutsideScope()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, int x2) in M()) { }
System.Console.Write(x1);
}
static (int, int)[] M() { return new[] { (1, 2) }; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,30): error CS0103: The name 'x1' does not exist in the current context
// System.Console.Write(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 30)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachNoIEnumerable()
{
string source = @"
class C
{
static void Main()
{
foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
";
string expectedOperationTree = @"
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1579: foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator'
// foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
Diagnostic(ErrorCode.ERR_ForEachMissingMember, "1").WithArguments("int", "GetEnumerator").WithLocation(6, 55),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 33),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 37)
};
VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachIterationVariablesAreReadonly()
{
string source = @"
class C
{
static void Main()
{
foreach (/*<bind>*/(int x1, var (x2, x3))/*</bind>*/ in new[] { (1, (1, 1)) })
{
x1 = 1;
x2 = 2;
x3 = 3;
}
}
}
";
string expectedOperationTree = @"
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, (System.Int32 x2, System.Int32 x3))) (Syntax: '(int x1, var (x2, x3))')
NaturalType: (System.Int32 x1, (System.Int32 x2, System.Int32 x3))
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x2, System.Int32 x3)) (Syntax: 'var (x2, x3)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x2, System.Int32 x3)) (Syntax: '(x2, x3)')
NaturalType: (System.Int32 x2, System.Int32 x3)
Elements(2):
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1656: Cannot assign to 'x1' because it is a 'foreach iteration variable'
// x1 = 1;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x1").WithArguments("x1", "foreach iteration variable").WithLocation(8, 13),
// CS1656: Cannot assign to 'x2' because it is a 'foreach iteration variable'
// x2 = 2;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x2").WithArguments("x2", "foreach iteration variable").WithLocation(9, 13),
// CS1656: Cannot assign to 'x3' because it is a 'foreach iteration variable'
// x3 = 3;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x3").WithArguments("x3", "foreach iteration variable").WithLocation(10, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void ForEachScoping()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M(x1)) { }
}
static (int, int) M(int i) { return (1, 2); }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,36): error CS0103: The name 'x1' does not exist in the current context
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 36),
// (6,34): error CS1579: foreach statement cannot operate on variables of type '(int, int)' because '(int, int)' does not contain a public instance or extension definition for 'GetEnumerator'
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_ForEachMissingMember, "M(x1)").WithArguments("(int, int)", "GetEnumerator").WithLocation(6, 34),
// (6,23): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 23),
// (6,27): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 27)
);
}
[Fact]
public void AssignmentDataFlow()
{
string source = @"
class C
{
static void Main()
{
int x, y;
(x, y) = new C(); // x and y are assigned here, so no complaints on usage of un-initialized locals on the line below
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void GetTypeInfoForTupleLiteral()
{
var source = @"
class C
{
static void Main()
{
var x1 = (1, 2);
var (x2, x3) = (1, 2);
System.Console.Write($""{x1} {x2} {x3}"");
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var literal1 = nodes.OfType<TupleExpressionSyntax>().First();
Assert.Equal("(int, int)", model.GetTypeInfo(literal1).Type.ToDisplayString());
var literal2 = nodes.OfType<TupleExpressionSyntax>().Skip(1).First();
Assert.Equal("(int, int)", model.GetTypeInfo(literal2).Type.ToDisplayString());
};
var verifier = CompileAndVerify(source, sourceSymbolValidator: validator);
verifier.VerifyDiagnostics();
}
[Fact]
public void DeclarationWithCircularity3()
{
string source = @"
class C
{
static void Main()
{
var (x1, x2) = (M(out x2), M(out x1));
}
static T M<T>(out T x) { x = default(T); return x; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,31): error CS0841: Cannot use local variable 'x2' before it is declared
// var (x1, x2) = (M(out x2), M(out x1));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(6, 31),
// (6,42): error CS0841: Cannot use local variable 'x1' before it is declared
// var (x1, x2) = (M(out x2), M(out x1));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 42)
);
}
[Fact, WorkItem(13081, "https://github.com/dotnet/roslyn/issues/13081")]
public void GettingDiagnosticsWhenValueTupleIsMissing()
{
var source = @"
class C1
{
static void Test(int arg1, (byte, byte) arg2)
{
foreach ((int, int) e in new (int, int)[10])
{
}
}
}
";
var comp = CreateCompilationWithMscorlib40(source);
comp.VerifyDiagnostics(
// (4,32): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// static void Test(int arg1, (byte, byte) arg2)
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(byte, byte)").WithArguments("System.ValueTuple`2").WithLocation(4, 32),
// (6,38): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// foreach ((int, int) e in new (int, int)[10])
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(6, 38),
// (6,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// foreach ((int, int) e in new (int, int)[10])
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(6, 18)
);
// no crash
}
[Fact]
public void DeconstructionMayBeEmbedded()
{
var source = @"
class C1
{
void M()
{
if (true)
var (x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// this is no longer considered a declaration statement,
// but rather is an assignment expression. So no error.
);
}
[Fact]
public void AssignmentExpressionCanBeUsedInEmbeddedStatement()
{
var source = @"
class C1
{
void M()
{
int x, y;
if (true)
(x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructObsoleteWarning()
{
var source = @"
class C
{
void M()
{
(int y1, int y2) = new C();
}
[System.Obsolete()]
void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,27): warning CS0612: 'C.Deconstruct(out int, out int)' is obsolete
// (int y1, int y2) = new C();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out int)").WithLocation(6, 27)
);
}
[Fact]
public void DeconstructObsoleteError()
{
var source = @"
class C
{
void M()
{
(int y1, int y2) = new C();
}
[System.Obsolete(""Deprecated"", error: true)]
void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,27): error CS0619: 'C.Deconstruct(out int, out int)' is obsolete: 'Deprecated'
// (int y1, int y2) = new C();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "new C()").WithArguments("C.Deconstruct(out int, out int)", "Deprecated").WithLocation(6, 27)
);
}
[Fact]
public void DeconstructionLocalsDeclaredNotUsed()
{
// Check that there are no *use sites* within this code for local variables.
// They are not declared. So they should not be returned
// by SemanticModel.GetSymbolInfo. Similarly, check that all designation syntax
// forms declare deconstruction locals.
string source = @"
class Program
{
static void Main()
{
var (x1, y1) = (1, 2);
(var x2, var y2) = (1, 2);
}
static void M((int, int) t)
{
var (x3, y3) = t;
(var x4, var y4) = t;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
foreach (var node in nodes)
{
var si = model.GetSymbolInfo(node);
var symbol = si.Symbol;
if ((object)symbol != null)
{
if (node is DeclarationExpressionSyntax)
{
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal(LocalDeclarationKind.DeconstructionVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
}
else
{
Assert.NotEqual(SymbolKind.Local, symbol.Kind);
}
}
symbol = model.GetDeclaredSymbol(node);
if ((object)symbol != null)
{
if (node is SingleVariableDesignationSyntax)
{
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal(LocalDeclarationKind.DeconstructionVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
}
else
{
Assert.NotEqual(SymbolKind.Local, symbol.Kind);
}
}
}
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(14287, "https://github.com/dotnet/roslyn/issues/14287")]
public void TupleDeconstructionStatementWithTypesCannotBeConst()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/const (int x, int y) = (1, 2);/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const (int ... ) = (1, 2);')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: '(int x, int y) = (1, 2)')
Declarators:
IVariableDeclaratorOperation (Symbol: (System.Int32 x, System.Int32 y) ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '= (1, 2)')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (1, 2)')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32 x, System.Int32 y), IsImplicit) (Syntax: '(1, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1001: Identifier expected
// const /*<bind>*/(int x, int y) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "=").WithLocation(6, 40),
// CS0283: The type '(int x, int y)' cannot be declared const
// const /*<bind>*/(int x, int y) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadConstType, "(int x, int y)").WithArguments("(int x, int y)").WithLocation(6, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(14287, "https://github.com/dotnet/roslyn/issues/14287")]
public void TupleDeconstructionStatementWithoutTypesCannotBeConst()
{
string source = @"
class C
{
static void Main()
{
const var (x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0106: The modifier 'const' is not valid for this item
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_BadMemberFlag, "const").WithArguments("const").WithLocation(6, 9),
// (6,19): error CS1001: Identifier expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(6, 19),
// (6,21): error CS1001: Identifier expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(6, 21),
// (6,24): error CS1001: Identifier expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 24),
// (6,26): error CS1002: ; expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(6, 26),
// (6,26): error CS1525: Invalid expression term '='
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(6, 26),
// (6,19): error CS8112: '(x, y)' is a local function and must therefore always have a body.
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "").WithArguments("(x, y)").WithLocation(6, 19),
// (6,20): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(6, 20),
// (6,23): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?)
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(6, 23),
// (6,15): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 15)
);
}
[Fact, WorkItem(15934, "https://github.com/dotnet/roslyn/issues/15934")]
public void PointerTypeInDeconstruction()
{
string source = @"
unsafe class C
{
static void Main(C c)
{
(int* x1, int y1) = c;
(var* x2, int y2) = c;
(int*[] x3, int y3) = c;
(var*[] x4, int y4) = c;
}
public void Deconstruct(out dynamic x, out dynamic y)
{
x = y = null;
}
}
";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source,
references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.UnsafeDebugDll,
parseOptions: TestOptions.RegularPreview);
// The precise diagnostics here are not important, and may be sensitive to parser
// adjustments. This is a test that we don't crash. The errors here are likely to
// change as we adjust the parser and semantic analysis of error cases.
comp.VerifyDiagnostics(
// (6,10): error CS1525: Invalid expression term 'int'
// (int* x1, int y1) = c;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 10),
// (6,15): error CS0103: The name 'x1' does not exist in the current context
// (int* x1, int y1) = c;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 15),
// (6,19): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (int* x1, int y1) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y1").WithArguments("dynamic", "int").WithLocation(6, 19),
// (7,10): error CS0103: The name 'var' does not exist in the current context
// (var* x2, int y2) = c;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 10),
// (7,15): error CS0103: The name 'x2' does not exist in the current context
// (var* x2, int y2) = c;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 15),
// (7,19): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (var* x2, int y2) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y2").WithArguments("dynamic", "int").WithLocation(7, 19),
// (8,10): error CS0266: Cannot implicitly convert type 'dynamic' to 'int*[]'. An explicit conversion exists (are you missing a cast?)
// (int*[] x3, int y3) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int*[] x3").WithArguments("dynamic", "int*[]").WithLocation(8, 10),
// (8,21): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (int*[] x3, int y3) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y3").WithArguments("dynamic", "int").WithLocation(8, 21),
// (9,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(9, 10),
// (9,10): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('var')
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_ManagedAddr, "var*").WithArguments("var").WithLocation(9, 10),
// (9,10): error CS0266: Cannot implicitly convert type 'dynamic' to 'var*[]'. An explicit conversion exists (are you missing a cast?)
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "var*[] x4").WithArguments("dynamic", "var*[]").WithLocation(9, 10),
// (9,21): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y4").WithArguments("dynamic", "int").WithLocation(9, 21)
);
}
[Fact]
public void DeclarationInsideNameof()
{
string source = @"
class Program
{
static void Main()
{
string s = nameof((int x1, var x2) = (1, 2)).ToString();
string s1 = x1, s2 = x2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,28): error CS8185: A declaration is not allowed in this context.
// string s = nameof((int x1, var x2) = (1, 2)).ToString();
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 28),
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof((int x1, var x2) = (1, 2)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(int x1, var x2) = (1, 2)").WithLocation(6, 27),
// (7,21): error CS0029: Cannot implicitly convert type 'int' to 'string'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("int", "string").WithLocation(7, 21),
// (7,30): error CS0029: Cannot implicitly convert type 'int' to 'string'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("int", "string").WithLocation(7, 30),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 21),
// (7,30): error CS0165: Use of unassigned local variable 'x2'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(7, 30)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(2, designations.Count());
var refs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>();
var x1 = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("x1", x1.Name);
Assert.Equal("System.Int32", ((ILocalSymbol)x1).Type.ToTestDisplayString());
Assert.Same(x1, model.GetSymbolInfo(refs.Where(r => r.Identifier.ValueText == "x1").Single()).Symbol);
var x2 = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("x2", x2.Name);
Assert.Equal("System.Int32", ((ILocalSymbol)x2).Type.ToTestDisplayString());
Assert.Same(x2, model.GetSymbolInfo(refs.Where(r => r.Identifier.ValueText == "x2").Single()).Symbol);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_01()
{
string source1 = @"
class C
{
static void Main()
{
(var (a,b), var c, int d);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)"),
// (6,21): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c"),
// (6,28): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(6, 28),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (a,b), var c, int d)").WithLocation(6, 9),
// (6,28): error CS0165: Use of unassigned local variable 'd'
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int d").WithArguments("d").WithLocation(6, 28)
);
StandAlone_01_VerifySemanticModel(comp1, LocalDeclarationKind.DeclarationExpressionVariable);
string source2 = @"
class C
{
static void Main()
{
(var (a,b), var c, int d) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_01_VerifySemanticModel(comp2, LocalDeclarationKind.DeconstructionVariable);
}
private static void StandAlone_01_VerifySemanticModel(CSharpCompilation comp, LocalDeclarationKind localDeclarationKind)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var a", a.ToTestDisplayString());
Assert.Equal(localDeclarationKind, a.GetSymbol<LocalSymbol>().DeclarationKind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var b", b.ToTestDisplayString());
Assert.Equal(localDeclarationKind, b.GetSymbol<LocalSymbol>().DeclarationKind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var c", c.ToTestDisplayString());
Assert.Equal(localDeclarationKind, c.GetSymbol<LocalSymbol>().DeclarationKind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 d", d.ToTestDisplayString());
Assert.Equal(localDeclarationKind, d.GetSymbol<LocalSymbol>().DeclarationKind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("((var a, var b), var c, System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_02()
{
string source1 = @"
(var (a,b), var c, int d);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,7): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a"),
// (2,9): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b"),
// (2,17): error CS7019: Type of 'c' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "c").WithArguments("c"),
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)"),
// (2,13): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c"),
// (2,20): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(2, 20),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (a,b), var c, int d)").WithLocation(2, 1)
);
StandAlone_02_VerifySemanticModel(comp1);
string source2 = @"
(var (a,b), var c, int d) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_02_VerifySemanticModel(comp2);
}
private static void StandAlone_02_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var Script.a", a.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, a.Kind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var Script.b", b.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, b.Kind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var Script.c", c.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, c.Kind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 Script.d", d.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, d.Kind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var Script.c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 Script.d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("((var a, var b), var c, System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_03()
{
string source1 = @"
class C
{
static void Main()
{
(var (_, _), var _, int _);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)"),
// (6,22): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _"),
// (6,29): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(6, 29),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (_, _), var _, int _)").WithLocation(6, 9)
);
StandAlone_03_VerifySemanticModel(comp1);
string source2 = @"
class C
{
static void Main()
{
(var (_, _), var _, int _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_03_VerifySemanticModel(comp2);
}
private static void StandAlone_03_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
int count = 0;
foreach (var designation in tree.GetCompilationUnitRoot().DescendantNodes().OfType<DiscardDesignationSyntax>())
{
Assert.Null(model.GetDeclaredSymbol(designation));
count++;
}
Assert.Equal(4, count);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (_, _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var, var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int _", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("((var, var), var, System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_04()
{
string source1 = @"
(var (_, _), var _, int _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)"),
// (2,14): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _"),
// (2,21): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(2, 21),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (_, _), var _, int _)").WithLocation(2, 1)
);
StandAlone_03_VerifySemanticModel(comp1);
string source2 = @"
(var (_, _), var _, int _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_03_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_05()
{
string source1 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (a,b), var c);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_05_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (a,b), var c) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_05_VerifySemanticModel(comp2);
}
private static void StandAlone_05_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(System.Int32 a, System.Int32 b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[0].Type).ToTestDisplayString());
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[1].Type).ToTestDisplayString());
}
[Fact]
[WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")]
public void StandAlone_05_WithDuplicateNames()
{
string source1 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (a, a), var c);
}
}
";
var comp1 = CreateCompilation(source1);
var tree = comp1.SyntaxTrees.Single();
var model = comp1.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var aa = nodes.OfType<DeclarationExpressionSyntax>().ElementAt(0);
Assert.Equal("var (a, a)", aa.ToString());
var aaType = model.GetTypeInfo(aa).Type.GetSymbol();
Assert.True(aaType.TupleElementNames.IsDefault);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_06()
{
string source1 = @"
using var = System.Int32;
(var (a,b), var c);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_06_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
(var (a,b), var c) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_06_VerifySemanticModel(comp2);
}
private static void StandAlone_06_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(System.Int32 a, System.Int32 b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[0].Type).ToTestDisplayString());
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 Script.c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[1].Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_07()
{
string source1 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (_, _), var _);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_07_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (_, _), var _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_07_VerifySemanticModel(comp2);
}
private static void StandAlone_07_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var (_, _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(System.Int32, System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[0].Type).ToTestDisplayString());
Assert.Equal("var _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[1].Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_08()
{
string source1 = @"
using var = System.Int32;
(var (_, _), var _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_07_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
(var (_, _), var _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_07_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_09()
{
string source1 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (a,b), al c);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_09_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (a,b), al c) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_09_VerifySemanticModel(comp2);
}
private static void StandAlone_09_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
Assert.Equal("al c", declaration.ToString());
var typeInfo = model.GetTypeInfo(declaration);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration).IsIdentity);
Assert.Equal("System.Int32 c", model.GetSymbolInfo(declaration).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration.Type).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declaration.Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("al=System.Int32", model.GetAliasInfo(declaration.Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_10()
{
string source1 = @"
using al = System.Int32;
(al (a,b), al c);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_10_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
(al (a,b), al c) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_10_VerifySemanticModel(comp2);
}
private static void StandAlone_10_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
Assert.Equal("al c", declaration.ToString());
var typeInfo = model.GetTypeInfo(declaration);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration).IsIdentity);
Assert.Equal("System.Int32 Script.c", model.GetSymbolInfo(declaration).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration.Type).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declaration.Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("al=System.Int32", model.GetAliasInfo(declaration.Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_11()
{
string source1 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (_, _), al _);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_11_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (_, _), al _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_11_VerifySemanticModel(comp2);
}
private static void StandAlone_11_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
Assert.Equal("al _", declaration.ToString());
var typeInfo = model.GetTypeInfo(declaration);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declaration);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declaration.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration.Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declaration.Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("al=System.Int32", model.GetAliasInfo(declaration.Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_12()
{
string source1 = @"
using al = System.Int32;
(al (_, _), al _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_11_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
(al (_, _), al _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_11_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_13()
{
string source1 = @"
class C
{
static void Main()
{
var (a, b);
var (c, d)
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (7,19): error CS1002: ; expected
// var (c, d)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 19),
// (6,9): error CS0103: The name 'var' does not exist in the current context
// var (a, b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9),
// (6,14): error CS0103: The name 'a' does not exist in the current context
// var (a, b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 14),
// (6,17): error CS0103: The name 'b' does not exist in the current context
// var (a, b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(6, 17),
// (7,9): error CS0103: The name 'var' does not exist in the current context
// var (c, d)
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 9),
// (7,14): error CS0103: The name 'c' does not exist in the current context
// var (c, d)
Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c").WithLocation(7, 14),
// (7,17): error CS0103: The name 'd' does not exist in the current context
// var (c, d)
Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d").WithLocation(7, 17)
);
var tree = comp1.SyntaxTrees.First();
Assert.False(tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_14()
{
string source1 = @"
class C
{
static void Main()
{
((var (a,b), var c), int d);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,11): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)").WithLocation(6, 11),
// (6,22): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c").WithLocation(6, 22),
// (6,30): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(6, 30),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (a,b), var c), int d)").WithLocation(6, 9),
// (6,30): error CS0165: Use of unassigned local variable 'd'
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int d").WithArguments("d").WithLocation(6, 30)
);
StandAlone_14_VerifySemanticModel(comp1, LocalDeclarationKind.DeclarationExpressionVariable);
string source2 = @"
class C
{
static void Main()
{
((var (a,b), var c), int d) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_14_VerifySemanticModel(comp2, LocalDeclarationKind.DeconstructionVariable);
}
private static void StandAlone_14_VerifySemanticModel(CSharpCompilation comp, LocalDeclarationKind localDeclarationKind)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var a", a.ToTestDisplayString());
Assert.Equal(localDeclarationKind, a.GetSymbol<LocalSymbol>().DeclarationKind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var b", b.ToTestDisplayString());
Assert.Equal(localDeclarationKind, b.GetSymbol<LocalSymbol>().DeclarationKind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var c", c.ToTestDisplayString());
Assert.Equal(localDeclarationKind, c.GetSymbol<LocalSymbol>().DeclarationKind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 d", d.ToTestDisplayString());
Assert.Equal(localDeclarationKind, d.GetSymbol<LocalSymbol>().DeclarationKind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ToArray();
Assert.Equal(2, tuples.Length);
Assert.Equal("((var (a,b), var c), int d)", tuples[0].ToString());
typeInfo = model.GetTypeInfo(tuples[0]);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[0]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("(var (a,b), var c)", tuples[1].ToString());
typeInfo = model.GetTypeInfo(tuples[1]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_15()
{
string source1 = @"
((var (a,b), var c), int d);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,8): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(2, 8),
// (2,10): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(2, 10),
// (2,18): error CS7019: Type of 'c' cannot be inferred since its initializer directly or indirectly refers to the definition.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "c").WithArguments("c").WithLocation(2, 18),
// (2,3): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)").WithLocation(2, 3),
// (2,14): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c").WithLocation(2, 14),
// (2,22): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(2, 22),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (a,b), var c), int d)").WithLocation(2, 1)
);
StandAlone_15_VerifySemanticModel(comp1);
string source2 = @"
((var (a,b), var c), int d) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_15_VerifySemanticModel(comp2);
}
private static void StandAlone_15_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var Script.a", a.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, a.Kind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var Script.b", b.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, b.Kind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var Script.c", c.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, c.Kind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 Script.d", d.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, d.Kind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var Script.c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 Script.d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ToArray();
Assert.Equal(2, tuples.Length);
Assert.Equal("((var (a,b), var c), int d)", tuples[0].ToString());
typeInfo = model.GetTypeInfo(tuples[0]);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[0]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("(var (a,b), var c)", tuples[1].ToString());
typeInfo = model.GetTypeInfo(tuples[1]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_16()
{
string source1 = @"
class C
{
static void Main()
{
((var (_, _), var _), int _);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,11): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)").WithLocation(6, 11),
// (6,23): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _").WithLocation(6, 23),
// (6,31): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(6, 31),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (_, _), var _), int _)").WithLocation(6, 9)
);
StandAlone_16_VerifySemanticModel(comp1);
string source2 = @"
class C
{
static void Main()
{
((var (_, _), var _), int _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_16_VerifySemanticModel(comp2);
}
private static void StandAlone_16_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
int count = 0;
foreach (var designation in tree.GetCompilationUnitRoot().DescendantNodes().OfType<DiscardDesignationSyntax>())
{
Assert.Null(model.GetDeclaredSymbol(designation));
count++;
}
Assert.Equal(4, count);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (_, _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var, var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int _", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ToArray();
Assert.Equal(2, tuples.Length);
Assert.Equal("((var (_, _), var _), int _)", tuples[0].ToString());
typeInfo = model.GetTypeInfo(tuples[0]);
Assert.Equal("(((var, var), var), System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[0]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("(var (_, _), var _)", tuples[1].ToString());
typeInfo = model.GetTypeInfo(tuples[1]);
Assert.Equal("((var, var), var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_17()
{
string source1 = @"
((var (_, _), var _), int _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,3): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)").WithLocation(2, 3),
// (2,15): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _").WithLocation(2, 15),
// (2,23): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(2, 23),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (_, _), var _), int _)").WithLocation(2, 1)
);
StandAlone_16_VerifySemanticModel(comp1);
string source2 = @"
((var (_, _), var _), int _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_16_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_18()
{
string source1 = @"
class C
{
static void Main()
{
(var ((a,b), c), int d);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((a,b), c)").WithLocation(6, 10),
// (6,26): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(6, 26),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((a,b), c), int d)").WithLocation(6, 9),
// (6,26): error CS0165: Use of unassigned local variable 'd'
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int d").WithArguments("d").WithLocation(6, 26)
);
StandAlone_18_VerifySemanticModel(comp1, LocalDeclarationKind.DeclarationExpressionVariable);
string source2 = @"
class C
{
static void Main()
{
(var ((a,b), c), int d) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_18_VerifySemanticModel(comp2, LocalDeclarationKind.DeconstructionVariable);
}
private static void StandAlone_18_VerifySemanticModel(CSharpCompilation comp, LocalDeclarationKind localDeclarationKind)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var a", a.ToTestDisplayString());
Assert.Equal(localDeclarationKind, a.GetSymbol<LocalSymbol>().DeclarationKind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var b", b.ToTestDisplayString());
Assert.Equal(localDeclarationKind, b.GetSymbol<LocalSymbol>().DeclarationKind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var c", c.ToTestDisplayString());
Assert.Equal(localDeclarationKind, c.GetSymbol<LocalSymbol>().DeclarationKind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 d", d.ToTestDisplayString());
Assert.Equal(localDeclarationKind, d.GetSymbol<LocalSymbol>().DeclarationKind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var ((a,b), c)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("int d", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 d", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[1].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_19()
{
string source1 = @"
(var ((a,b), c), int d);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,8): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(2, 8),
// (2,10): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(2, 10),
// (2,14): error CS7019: Type of 'c' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "c").WithArguments("c").WithLocation(2, 14),
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((a,b), c)").WithLocation(2, 2),
// (2,18): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(2, 18),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((a,b), c), int d)").WithLocation(2, 1)
);
StandAlone_19_VerifySemanticModel(comp1);
string source2 = @"
(var ((a,b), c), int d) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_19_VerifySemanticModel(comp2);
}
private static void StandAlone_19_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var Script.a", a.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, a.Kind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var Script.b", b.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, b.Kind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var Script.c", c.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, c.Kind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 Script.d", d.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, d.Kind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var ((a,b), c)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("int d", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 Script.d", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[1].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_20()
{
string source1 = @"
class C
{
static void Main()
{
(var ((_, _), _), int _);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((_, _), _)").WithLocation(6, 10),
// (6,27): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(6, 27),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((_, _), _), int _)").WithLocation(6, 9)
);
StandAlone_20_VerifySemanticModel(comp1);
string source2 = @"
class C
{
static void Main()
{
(var ((_, _), _), int _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_20_VerifySemanticModel(comp2);
}
private static void StandAlone_20_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
int count = 0;
foreach (var designation in tree.GetCompilationUnitRoot().DescendantNodes().OfType<DiscardDesignationSyntax>())
{
Assert.Null(model.GetDeclaredSymbol(designation));
count++;
}
Assert.Equal(4, count);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var ((_, _), _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("((var, var), var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("int _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[1].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("(((var, var), var), System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_21()
{
string source1 = @"
(var ((_, _), _), int _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((_, _), _)").WithLocation(2, 2),
// (2,19): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(2, 19),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((_, _), _), int _)").WithLocation(2, 1)
);
StandAlone_20_VerifySemanticModel(comp1);
string source2 = @"
(var ((_, _), _), int _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_20_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DiscardVoid_01()
{
var source = @"class C
{
static void Main()
{
(_, _) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,22): error CS8210: A tuple may not contain a value of type 'void'.
// (_, _) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 22)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_01()
{
var source = @"class C
{
static void Main()
{
(int x, void y) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS1547: Keyword 'void' cannot be used in this context
// (int x, void y) = (1, Main());
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(5, 17),
// (5,31): error CS8210: A tuple may not contain a value of type 'void'.
// (int x, void y) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 31)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_02()
{
var source = @"class C
{
static void Main()
{
var (x, y) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,26): error CS8210: A tuple may not contain a value of type 'void'.
// var (x, y) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 26)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_03()
{
var source = @"class C
{
static void Main()
{
(int x, void y) = (1, 2);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS1547: Keyword 'void' cannot be used in this context
// (int x, void y) = (1, 2);
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(5, 17),
// (5,31): error CS0029: Cannot implicitly convert type 'int' to 'void'
// (int x, void y) = (1, 2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "void").WithLocation(5, 31)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var two = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "2").Single();
var type = model.GetTypeInfo(two);
Assert.Equal(SpecialType.System_Int32, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Int32, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(two).Kind);
var symbols = model.GetSymbolInfo(two);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)two.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_04()
{
var source = @"class C
{
static void Main()
{
(int x, int y) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,30): error CS8210: A tuple may not contain a value of type 'void'.
// (int x, int y) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 30)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DiscardDeclarationExpression_IOperation()
{
string source = @"
class C
{
void M()
{
/*<bind>*/var (_, _) = (0, 0)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32)) (Syntax: 'var (_, _) = (0, 0)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32, System.Int32)) (Syntax: 'var (_, _)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(_, _)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(0, 0)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DiscardDeclarationAssignment_IOperation()
{
string source = @"
class C
{
void M()
{
int x;
/*<bind>*/(x, _) = (0, 0)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, _) = (0, 0)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, _)')
NaturalType: (System.Int32 x, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(0, 0)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DiscardOutVarDeclaration_IOperation()
{
string source = @"
class C
{
void M()
{
M2(out /*<bind>*/var _/*</bind>*/);
}
void M2(out int x)
{
x = 0;
}
}
";
string expectedOperationTree = @"
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: 'var _')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_1()
{
var text = @"
class C
{
static void Main()
{
foreach ((var i, i))
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var i, i)").WithLocation(6, 18),
// (6,23): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'i'.
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "i").WithArguments("i").WithLocation(6, 23),
// (6,26): error CS0841: Cannot use local variable 'i' before it is declared
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "i").WithArguments("i").WithLocation(6, 26),
// (6,28): error CS1515: 'in' expected
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_InExpected, ")").WithLocation(6, 28),
// (6,28): error CS1525: Invalid expression term ')'
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 28),
// (6,29): error CS1525: Invalid expression term '}'
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}").WithLocation(6, 29),
// (6,29): error CS1002: ; expected
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 29)
);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_2()
{
var text = @"
class C
{
static void Main()
{
(var i, i) = ;
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'i'.
// (var i, i) = ;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "i").WithArguments("i").WithLocation(6, 14),
// (6,17): error CS0841: Cannot use local variable 'i' before it is declared
// (var i, i) = ;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "i").WithArguments("i").WithLocation(6, 17),
// (6,22): error CS1525: Invalid expression term ';'
// (var i, i) = ;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_3()
{
var text = @"
class C
{
static void Main()
{
foreach ((int i, i))
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int i, i)").WithLocation(6, 18),
// (6,26): error CS1656: Cannot assign to 'i' because it is a 'foreach iteration variable'
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "foreach iteration variable").WithLocation(6, 26),
// (6,28): error CS1515: 'in' expected
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_InExpected, ")").WithLocation(6, 28),
// (6,28): error CS1525: Invalid expression term ')'
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 28),
// (6,29): error CS1525: Invalid expression term '}'
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}").WithLocation(6, 29),
// (6,29): error CS1002: ; expected
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 29)
);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_4()
{
var text = @"
class C
{
static void Main()
{
(int i, i) = ;
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,22): error CS1525: Invalid expression term ';'
// (int i, i) = ;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 22)
);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics
{
[CompilerTrait(CompilerFeature.Tuples)]
public class DeconstructionTests : CompilingTestBase
{
private static readonly MetadataReference[] s_valueTupleRefs = new[] { SystemRuntimeFacadeRef, ValueTupleRef };
const string commonSource =
@"public class Pair<T1, T2>
{
T1 item1;
T2 item2;
public Pair(T1 item1, T2 item2)
{
this.item1 = item1;
this.item2 = item2;
}
public void Deconstruct(out T1 item1, out T2 item2)
{
System.Console.WriteLine($""Deconstructing {ToString()}"");
item1 = this.item1;
item2 = this.item2;
}
public override string ToString() { return $""({item1.ToString()}, {item2.ToString()})""; }
}
public static class Pair
{
public static Pair<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return new Pair<T1, T2>(item1, item2); }
}
public class Integer
{
public int state;
public override string ToString() { return state.ToString(); }
public Integer(int i) { state = i; }
public static implicit operator LongInteger(Integer i) { System.Console.WriteLine($""Converting {i}""); return new LongInteger(i.state); }
}
public class LongInteger
{
long state;
public LongInteger(long l) { state = l; }
public override string ToString() { return state.ToString(); }
}";
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodMissing()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C()").WithArguments("C", "Deconstruct").WithLocation(8, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWrongParams()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a) // too few arguments
{
a = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1501: No overload for method 'Deconstruct' takes 2 arguments
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("Deconstruct", "2").WithLocation(8, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWrongParams2()
{
string source = @"
class C
{
static void Main()
{
long x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a, out int b, out int c) // too many arguments
{
a = b = c = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.Int64 y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.Int64 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter 'c' of 'C.Deconstruct(out int, out int, out int)'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("c", "C.Deconstruct(out int, out int, out int)").WithLocation(7, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignmentWithLeftHandSideErrors()
{
string source = @"
class C
{
static void Main()
{
long x = 1;
string y = ""hello"";
/*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
}
public void Deconstruct() { }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x.f, y.g) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (? f, ? g), IsInvalid) (Syntax: '(x.f, y.g)')
NaturalType: (? f, ? g)
Elements(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.f')
Children(1):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y.g')
Children(1):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'long' does not contain a definition for 'f' and no extension method 'f' accepting a first argument of type 'long' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "f").WithArguments("long", "f").WithLocation(8, 22),
// CS1061: 'string' does not contain a definition for 'g' and no extension method 'g' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "g").WithArguments("string", "g").WithLocation(8, 27),
// CS1501: No overload for method 'Deconstruct' takes 2 arguments
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("Deconstruct", "2").WithLocation(8, 32),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x.f, y.g) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWithInParam()
{
string source = @"
class C
{
static void Main()
{
int x;
int y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int x, int y) { x = 1; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1615: Argument 2 may not be passed with the 'out' keyword
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgExtraRef, "(x, y) = new C()").WithArguments("2", "out").WithLocation(8, 19),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructWithRefParam()
{
string source = @"
class C
{
static void Main()
{
int x;
int y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(ref int x, out int y) { x = 1; y = 2; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1620: Argument 1 must be passed with the 'ref' keyword
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadArgRef, "(x, y) = new C()").WithArguments("1", "ref").WithLocation(8, 19),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(8, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructManually()
{
string source = @"
struct C
{
static void Main()
{
long x;
string y;
C c = new C();
c.Deconstruct(out x, out y); // error
/*<bind>*/(x, y) = c/*</bind>*/;
}
void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y) = c')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1503: Argument 1: cannot convert from 'out long' to 'out int'
// c.Deconstruct(out x, out y); // error
Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "out long", "out int").WithLocation(10, 27)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodHasOptionalParam()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, int c = 42) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void BadDeconstructShadowsBaseDeconstruct()
{
string source = @"
class D
{
public void Deconstruct(out int a, out string b) { a = 2; b = ""world""; }
}
class C : D
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, int c = 42) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(13, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodHasParams()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out string b, params int[] c) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodHasArglist()
{
string source = @"
class C
{
static void Main()
{
long x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a, out string b, __arglist) // not a Deconstruct operator
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS7036: There is no argument given that corresponds to the required formal parameter '__arglist' of 'C.Deconstruct(out int, out string, __arglist)'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("__arglist", "C.Deconstruct(out int, out string, __arglist)").WithLocation(9, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructDelegate()
{
string source = @"
delegate void D1(out int x, out int y);
class C
{
public D1 Deconstruct; // not a Deconstruct operator
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
}
public static void DeconstructMethod(out int a, out int b) { a = 1; b = 2; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = ne ... uctMethod }')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C() { D ... uctMethod }')
Arguments(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ Deconstru ... uctMethod }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: D1, IsInvalid) (Syntax: 'Deconstruct ... tructMethod')
Left:
IFieldReferenceOperation: D1 C.Deconstruct (OperationKind.FieldReference, Type: D1, IsInvalid) (Syntax: 'Deconstruct')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'Deconstruct')
Right:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: D1, IsInvalid, IsImplicit) (Syntax: 'DeconstructMethod')
Target:
IMethodReferenceOperation: void C.DeconstructMethod(out System.Int32 a, out System.Int32 b) (Static) (OperationKind.MethodReference, Type: null, IsInvalid) (Syntax: 'DeconstructMethod')
Instance Receiver:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C() { Deconstruct = DeconstructMethod }").WithArguments("C", "2").WithLocation(11, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructDelegate2()
{
string source = @"
delegate void D1(out int x, out int y);
class C
{
public D1 Deconstruct;
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
}
public static void DeconstructMethod(out int a, out int b) { a = 1; b = 2; }
public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y), IsInvalid) (Syntax: '(x, y) = ne ... uctMethod }')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C() { D ... uctMethod }')
Arguments(0)
Initializer:
IObjectOrCollectionInitializerOperation (OperationKind.ObjectOrCollectionInitializer, Type: C, IsInvalid) (Syntax: '{ Deconstru ... uctMethod }')
Initializers(1):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'Deconstruct ... tructMethod')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'Deconstruct')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Deconstruct')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'C')
Right:
IOperation: (OperationKind.None, Type: null) (Syntax: 'DeconstructMethod')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C, IsImplicit) (Syntax: 'DeconstructMethod')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0102: The type 'C' already contains a definition for 'Deconstruct'
// public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "Deconstruct").WithArguments("C", "Deconstruct").WithLocation(16, 17),
// CS1913: Member 'Deconstruct' cannot be initialized. It is not a field or property.
// /*<bind>*/(x, y) = new C() { Deconstruct = DeconstructMethod }/*</bind>*/;
Diagnostic(ErrorCode.ERR_MemberCannotBeInitialized, "Deconstruct").WithArguments("Deconstruct").WithLocation(11, 38),
// CS0649: Field 'C.Deconstruct' is never assigned to, and will always have its default value null
// public D1 Deconstruct;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Deconstruct").WithArguments("C.Deconstruct", "null").WithLocation(6, 15)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructEvent()
{
string source = @"
delegate void D1(out int x, out int y);
class C
{
public event D1 Deconstruct; // not a Deconstruct operator
static void Main()
{
long x;
int y;
C c = new C();
c.Deconstruct += DeconstructMethod;
/*<bind>*/(x, y) = c/*</bind>*/;
}
public static void DeconstructMethod(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = c')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: C, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = c/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "c").WithArguments("C", "2").WithLocation(14, 28),
// CS0067: The event 'C.Deconstruct' is never used
// public event D1 Deconstruct; // not a Deconstruct operator
Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Deconstruct").WithArguments("C.Deconstruct").WithLocation(6, 21)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ConversionErrors()
{
string source = @"
class C
{
static void Main()
{
byte x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Byte x, System.String y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (System.Byte x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Byte, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0266: Cannot implicitly convert type 'int' to 'byte'. An explicit conversion exists (are you missing a cast?)
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("int", "byte").WithLocation(8, 20),
// CS0029: Cannot implicitly convert type 'int' to 'string'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "y").WithArguments("int", "string").WithLocation(8, 23)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void ExpressionType()
{
string source = @"
class C
{
static void Main()
{
int x, y;
var type = ((x, y) = new C()).GetType();
System.Console.Write(type.ToString());
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "System.ValueTuple`2[System.Int32,System.Int32]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ExpressionType_IOperation()
{
string source = @"
class C
{
static void Main()
{
int x, y;
var type = (/*<bind>*/(x, y) = new C()/*</bind>*/).GetType();
System.Console.Write(type.ToString());
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LambdaStillNotValidStatement()
{
string source = @"
class C
{
static void Main()
{
(a) => a;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (a) => a;
Diagnostic(ErrorCode.ERR_IllegalStatement, "(a) => a").WithLocation(6, 9)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void LambdaWithBodyStillNotValidStatement()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(a, b) => { }/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: '(a, b) => { }')
IBlockOperation (0 statements) (OperationKind.Block, Type: null, IsInvalid) (Syntax: '{ }')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// /*<bind>*/(a, b) => { }/*</bind>*/;
Diagnostic(ErrorCode.ERR_IllegalStatement, "(a, b) => { }").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<ParenthesizedLambdaExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void CastButNotCast()
{
// int and string must be types, so (int, string) must be type and ((int, string)) a cast, but then .String() cannot follow a cast...
string source = @"
class C
{
static void Main()
{
/*<bind>*/((int, string)).ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvocationOperation (virtual System.String (System.Int32, System.String).ToString()) (OperationKind.Invocation, Type: System.String, IsInvalid) (Syntax: '((int, stri ... .ToString()')
Instance Receiver:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.String), IsInvalid) (Syntax: '(int, string)')
NaturalType: (System.Int32, System.String)
Elements(2):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'int')
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'string')
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'int'
// /*<bind>*/((int, string)).ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 21),
// CS1525: Invalid expression term 'string'
// /*<bind>*/((int, string)).ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "string").WithArguments("string").WithLocation(6, 26)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningMethod2()
{
string source = @"
class C
{
static int i;
static void Main()
{
(M(), M()) = new C();
System.Console.Write(i);
}
static ref int M()
{
System.Console.Write(""M "");
return ref i;
}
void Deconstruct(out int i, out int j)
{
i = 42;
j = 43;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "M M 43");
comp.VerifyDiagnostics(
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningMethod2_IOperation()
{
string source = @"
class C
{
static int i;
static void Main()
{
/*<bind>*/(M(), M()) = new C()/*</bind>*/;
System.Console.Write(i);
}
static ref int M()
{
System.Console.Write(""M "");
return ref i;
}
void Deconstruct(out int i, out int j)
{
i = 42;
j = 43;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32)) (Syntax: '(M(), M()) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(M(), M())')
NaturalType: (System.Int32, System.Int32)
Elements(2):
IInvocationOperation (ref System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
IInvocationOperation (ref System.Int32 C.M()) (OperationKind.Invocation, Type: System.Int32) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UninitializedRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = x/*</bind>*/;
}
}
static class D
{
public static void Deconstruct(this int input, out int output, out int output2) { output = input; output2 = input; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(x, x) = x')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0165: Use of unassigned local variable 'x'
// /*<bind>*/(x, x) = x/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NullRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(x, x) = null')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/(x, x) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ErrorRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = undeclared/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(x, x) = undeclared')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'undeclared')
Children(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'undeclared' does not exist in the current context
// /*<bind>*/(x, x) = undeclared/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "undeclared").WithArguments("undeclared").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VoidRight()
{
string source = @"
class C
{
static void Main()
{
int x;
/*<bind>*/(x, x) = M()/*</bind>*/;
}
static void M() { }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, x) = M()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(x, x)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
Right:
IInvocationOperation (void C.M()) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'void' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'void' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(x, x) = M()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M()").WithArguments("void", "Deconstruct").WithLocation(7, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'void', with 2 out parameters and a void return type.
// /*<bind>*/(x, x) = M()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "M()").WithArguments("void", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssigningTupleWithNoConversion()
{
string source = @"
class C
{
static void Main()
{
byte x;
string y;
/*<bind>*/(x, y) = (1, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Byte x, System.String y), IsInvalid) (Syntax: '(x, y) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Byte x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Byte x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Byte) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Byte, System.String), IsInvalid, IsImplicit) (Syntax: '(1, 2)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0029: Cannot implicitly convert type 'int' to 'string'
// /*<bind>*/(x, y) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "string").WithLocation(9, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NotAssignable()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(1, P) = (1, 2)/*</bind>*/;
}
static int P { get { return 1; } }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32 P), IsInvalid) (Syntax: '(1, P) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32 P), IsInvalid) (Syntax: '(1, P)')
NaturalType: (System.Int32, System.Int32 P)
Elements(2):
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: '1')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
IInvalidOperation (OperationKind.Invalid, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'P')
Children(1):
IPropertyReferenceOperation: System.Int32 C.P { get; } (Static) (OperationKind.PropertyReference, Type: System.Int32, IsInvalid) (Syntax: 'P')
Instance Receiver:
null
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0131: The left-hand side of an assignment must be a variable, property or indexer
// /*<bind>*/(1, P) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "1").WithLocation(6, 20),
// CS0200: Property or indexer 'C.P' cannot be assigned to -- it is read only
// /*<bind>*/(1, P) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "P").WithArguments("C.P").WithLocation(6, 23)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void TupleWithUseSiteError()
{
string source = @"
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
}
}
}
class C
{
static void Main()
{
int x;
int y;
(x, y) = (1, 2);
System.Console.WriteLine($""{x} {y}"");
}
}
";
var comp = CreateCompilation(source, assemblyName: "comp", options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
comp.VerifyEmitDiagnostics();
CompileAndVerify(comp, expectedOutput: "1 2");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TupleWithUseSiteError_IOperation()
{
string source = @"
namespace System
{
struct ValueTuple<T1, T2>
{
public T1 Item1;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
}
}
}
class C
{
static void Main()
{
int x;
int y;
/*<bind>*/(x, y) = (1, 2)/*</bind>*/;
System.Console.WriteLine($""{x} {y}"");
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignUsingAmbiguousDeconstruction()
{
string source = @"
class Base
{
public void Deconstruct(out int a, out int b) { a = 1; b = 2; }
public void Deconstruct(out long a, out long b) { a = 1; b = 2; }
}
class C : Base
{
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
System.Console.WriteLine(x + "" "" + y);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// file.cs(12,28): error CS0121: The call is ambiguous between the following methods or properties: 'Base.Deconstruct(out int, out int)' and 'Base.Deconstruct(out long, out long)'
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_AmbigCall, "new C()").WithArguments("Base.Deconstruct(out int, out int)", "Base.Deconstruct(out long, out long)").WithLocation(12, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructIsDynamicField()
{
string source = @"
class C
{
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public dynamic Deconstruct = null;
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructIsField()
{
string source = @"
class C
{
static void Main()
{
int x, y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public object Deconstruct = null;
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.Int32 y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1955: Non-invocable member 'C.Deconstruct' cannot be used like a method.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_NonInvocableMemberCalled, "new C()").WithArguments("C.Deconstruct").WithLocation(7, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void CannotDeconstructRefTuple22()
{
string template = @"
using System;
class C
{
static void Main()
{
int VARIABLES; // int x1, x2, ...
(VARIABLES) = CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)));
}
public static Tuple<T1, T2, T3, T4, T5, T6, T7, TRest> CreateLongRef<T1, T2, T3, T4, T5, T6, T7, TRest>(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) =>
new Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>(item1, item2, item3, item4, item5, item6, item7, rest);
}
";
var tuple = String.Join(", ", Enumerable.Range(1, 22).Select(n => n.ToString()));
var variables = String.Join(", ", Enumerable.Range(1, 22).Select(n => $"x{n}"));
var source = template.Replace("VARIABLES", variables).Replace("TUPLE", tuple);
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,113): error CS1501: No overload for method 'Deconstruct' takes 22 arguments
// (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22) = CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)));
Diagnostic(ErrorCode.ERR_BadArgCount, "CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)))").WithArguments("Deconstruct", "22").WithLocation(8, 113),
// (8,113): error CS8129: No Deconstruct instance or extension method was found for type 'Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, int, int, int, Tuple<int, int, int, int, int, int, int, Tuple<int>>>>', with 22 out parameters.
// (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15, x16, x17, x18, x19, x20, x21, x22) = CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)));
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "CreateLongRef(1, 2, 3, 4, 5, 6, 7, CreateLongRef(8, 9, 10, 11, 12, 13, 14, Tuple.Create(15, 16, 17, 18, 19, 20, 21, 22)))").WithArguments("System.Tuple<int, int, int, int, int, int, int, System.Tuple<int, int, int, int, int, int, int, System.Tuple<int, int, int, int, int, int, int, System.Tuple<int>>>>", "22").WithLocation(8, 113)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructUsingDynamicMethod()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
dynamic c = new C();
/*<bind>*/(x, y) = c/*</bind>*/;
}
public void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = c')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: dynamic, IsInvalid) (Syntax: 'c')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8133: Cannot deconstruct dynamic objects.
// /*<bind>*/(x, y) = c/*</bind>*/;
Diagnostic(ErrorCode.ERR_CannotDeconstructDynamic, "c").WithLocation(10, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructMethodInaccessible()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
/*<bind>*/(x, y) = new C1()/*</bind>*/;
}
}
class C1
{
protected void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C1()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C1..ctor()) (OperationKind.ObjectCreation, Type: C1, IsInvalid) (Syntax: 'new C1()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0122: 'C1.Deconstruct(out int, out string)' is inaccessible due to its protection level
// /*<bind>*/(x, y) = new C1()/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadAccess, "new C1()").WithArguments("C1.Deconstruct(out int, out string)").WithLocation(9, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C1', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C1()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C1()").WithArguments("C1", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DeconstructHasUseSiteError()
{
string libMissingSource = @"public class Missing { }";
string libSource = @"
public class C
{
public void Deconstruct(out Missing a, out Missing b) { a = new Missing(); b = new Missing(); }
}
";
string source = @"
class C1
{
static void Main()
{
object x, y;
(x, y) = new C();
}
}
";
var libMissingComp = CreateCompilation(new string[] { libMissingSource }, assemblyName: "libMissingComp").VerifyDiagnostics();
var libMissingRef = libMissingComp.EmitToImageReference();
var libComp = CreateCompilation(new string[] { libSource }, references: new[] { libMissingRef }, parseOptions: TestOptions.Regular).VerifyDiagnostics();
var libRef = libComp.EmitToImageReference();
var comp = CreateCompilation(new string[] { source }, references: new[] { libRef });
comp.VerifyDiagnostics(
// (7,18): error CS0012: The type 'Missing' is defined in an assembly that is not referenced. You must add a reference to assembly 'libMissingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_NoTypeDef, "new C()").WithArguments("Missing", "libMissingComp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(7, 18),
// (7,18): error CS8129: No Deconstruct instance or extension method was found for type 'C', with 2 out parameters.
// (x, y) = new C();
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(7, 18)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void StaticDeconstruct()
{
string source = @"
class C
{
static void Main()
{
int x;
string y;
/*<bind>*/(x, y) = new C()/*</bind>*/;
}
public static void Deconstruct(out int a, out string b) { a = 1; b = ""hello""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int32 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C, IsInvalid) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0176: Member 'C.Deconstruct(out int, out string)' cannot be accessed with an instance reference; qualify it with a type name instead
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_ObjectProhibited, "new C()").WithArguments("C.Deconstruct(out int, out string)").WithLocation(9, 28),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type.
// /*<bind>*/(x, y) = new C()/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void AssignmentTypeIsValueTuple()
{
string source = @"
class C
{
public static void Main()
{
long x; string y;
var z1 = ((x, y) = new C()).ToString();
var z2 = ((x, y) = new C());
var z3 = (x, y) = new C();
System.Console.Write($""{z1} {z2.ToString()} {z3.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, hello) (1, hello) (1, hello)");
comp.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignmentTypeIsValueTuple_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x; string y;
var z1 = ((x, y) = new C()).ToString();
var z2 = (/*<bind>*/(x, y) = new C()/*</bind>*/);
var z3 = (x, y) = new C();
System.Console.Write($""{z1} {z2.ToString()} {z3.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x, System.String y)) (Syntax: '(x, y)')
NaturalType: (System.Int64 x, System.String y)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.String) (Syntax: 'y')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void NestedAssignmentTypeIsValueTuple()
{
string source = @"
class C
{
public static void Main()
{
long x1; string x2; int x3;
var y = ((x1, x2), x3) = (new C(), 3);
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "((1, hello), 3)");
comp.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NestedAssignmentTypeIsValueTuple_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x1; string x2; int x3;
var y = /*<bind>*/((x1, x2), x3) = (new C(), 3)/*</bind>*/;
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int a, out string b)
{
a = 1;
b = ""hello"";
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ((System.Int64 x1, System.String x2), System.Int32 x3)) (Syntax: '((x1, x2), ... new C(), 3)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((System.Int64 x1, System.String x2), System.Int32 x3)) (Syntax: '((x1, x2), x3)')
NaturalType: ((System.Int64 x1, System.String x2), System.Int32 x3)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.Int64 x1, System.String x2)) (Syntax: '(x1, x2)')
NaturalType: (System.Int64 x1, System.String x2)
Elements(2):
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x1')
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.String) (Syntax: 'x2')
ILocalReferenceOperation: x3 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x3')
Right:
ITupleOperation (OperationKind.Tuple, Type: (C, System.Int32)) (Syntax: '(new C(), 3)')
NaturalType: (C, System.Int32)
Elements(2):
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void AssignmentReturnsLongValueTuple()
{
string source = @"
class C
{
public static void Main()
{
long x;
var y = (x, x, x, x, x, x, x, x, x) = new C();
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int x1, out int x2, out int x3, out int x4, out int x5, out int x6, out int x7, out int x8, out int x9)
{
x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = 1;
x9 = 9;
}
}
";
var comp = CompileAndVerify(source, expectedOutput: "(1, 1, 1, 1, 1, 1, 1, 1, 9)");
comp.VerifyDiagnostics();
var tree = comp.Compilation.SyntaxTrees.First();
var model = comp.Compilation.GetSemanticModel(tree, ignoreAccessibility: false);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var y = nodes.OfType<VariableDeclaratorSyntax>().Skip(1).First();
Assert.Equal("y = (x, x, x, x, x, x, x, x, x) = new C()", y.ToFullString());
Assert.Equal("(System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64) y",
model.GetDeclaredSymbol(y).ToTestDisplayString());
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void AssignmentReturnsLongValueTuple_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x;
var /*<bind>*/y = (x, x, x, x, x, x, x, x, x) = new C()/*</bind>*/;
System.Console.Write($""{y.ToString()}"");
}
public void Deconstruct(out int x1, out int x2, out int x3, out int x4, out int x5, out int x6, out int x7, out int x8, out int x9)
{
x1 = x2 = x3 = x4 = x5 = x6 = x7 = x8 = 1;
x9 = 9;
}
}
";
string expectedOperationTree = @"
IVariableDeclaratorOperation (Symbol: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64) y) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'y = (x, x, ... ) = new C()')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null) (Syntax: '= (x, x, x, ... ) = new C()')
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64)) (Syntax: '(x, x, x, x ... ) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64)) (Syntax: '(x, x, x, x ... x, x, x, x)')
NaturalType: (System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64, System.Int64)
Elements(9):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<VariableDeclaratorSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DeconstructWithoutValueTupleLibrary()
{
string source = @"
class C
{
public static void Main()
{
long x;
var y = (x, x) = new C();
System.Console.Write(y.ToString());
}
public void Deconstruct(out int x1, out int x2)
{
x1 = x2 = 1;
}
}
";
var comp = CreateCompilationWithMscorlib40(source);
comp.VerifyDiagnostics(
// (7,17): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// var y = (x, x) = new C();
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(x, x)").WithArguments("System.ValueTuple`2").WithLocation(7, 17)
);
}
[Fact]
public void ChainedAssignment()
{
string source = @"
class C
{
public static void Main()
{
long x1, x2;
var y = (x1, x1) = (x2, x2) = new C();
System.Console.Write($""{y.ToString()} {x1} {x2}"");
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
var comp = CreateCompilation(source, options: TestOptions.DebugExe);
comp.VerifyDiagnostics();
CompileAndVerify(comp, expectedOutput: "(1, 1) 1 1");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ChainedAssignment_IOperation()
{
string source = @"
class C
{
public static void Main()
{
long x1, x2;
var y = /*<bind>*/(x1, x1) = (x2, x2) = new C()/*</bind>*/;
System.Console.Write($""{y.ToString()} {x1} {x2}"");
}
public void Deconstruct(out int a, out int b)
{
a = b = 1;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64, System.Int64)) (Syntax: '(x1, x1) = ... ) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64, System.Int64)) (Syntax: '(x1, x1)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x1')
Right:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int64, System.Int64)) (Syntax: '(x2, x2) = new C()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int64, System.Int64)) (Syntax: '(x2, x2)')
NaturalType: (System.Int64, System.Int64)
Elements(2):
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x2')
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.Int64) (Syntax: 'x2')
Right:
IObjectCreationOperation (Constructor: C..ctor()) (OperationKind.ObjectCreation, Type: C) (Syntax: 'new C()')
Arguments(0)
Initializer:
null
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NestedTypelessTupleAssignment2()
{
string source = @"
class C
{
static void Main()
{
int x, y, z; // int cannot be null
/*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
System.Console.WriteLine(""nothing"" + x + y + z);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, (System.Int32 y, System.Int32 z)), IsInvalid) (Syntax: '(x, (y, z)) ... ull, null))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, (System.Int32 y, System.Int32 z))) (Syntax: '(x, (y, z))')
NaturalType: (System.Int32 x, (System.Int32 y, System.Int32 z))
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 z)) (Syntax: '(y, z)')
NaturalType: (System.Int32 y, System.Int32 z)
Elements(2):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'y')
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'z')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, (System.Int32, System.Int32)), IsInvalid, IsImplicit) (Syntax: '(null, (null, null))')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: null, IsInvalid) (Syntax: '(null, (null, null))')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ITupleOperation (OperationKind.Tuple, Type: null, IsInvalid) (Syntax: '(null, null)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// /*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 34),
// CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// /*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 41),
// CS0037: Cannot convert null to 'int' because it is a non-nullable value type
// /*<bind>*/(x, (y, z)) = (null, (null, null))/*</bind>*/;
Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(8, 47)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TupleWithWrongCardinality()
{
string source = @"
class C
{
static void Main()
{
int x, y, z;
/*<bind>*/(x, y, z) = MakePair()/*</bind>*/;
}
public static (int, int) MakePair()
{
return (42, 42);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, y, z) = MakePair()')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32 y, System.Int32 z), IsInvalid) (Syntax: '(x, y, z)')
NaturalType: (System.Int32 x, System.Int32 y, System.Int32 z)
Elements(3):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
Right:
IInvocationOperation ((System.Int32, System.Int32) C.MakePair()) (OperationKind.Invocation, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'MakePair()')
Instance Receiver:
null
Arguments(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// /*<bind>*/(x, y, z) = MakePair()/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, y, z) = MakePair()").WithArguments("2", "3").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NestedTupleWithWrongCardinality()
{
string source = @"
class C
{
static void Main()
{
int x, y, z, w;
/*<bind>*/(x, (y, z, w)) = Pair.Create(42, (43, 44))/*</bind>*/;
}
}
" + commonSource;
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(x, (y, z, ... , (43, 44))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, (System.Int32 y, System.Int32 z, System.Int32 w)), IsInvalid) (Syntax: '(x, (y, z, w))')
NaturalType: (System.Int32 x, (System.Int32 y, System.Int32 z, System.Int32 w))
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 y, System.Int32 z, System.Int32 w), IsInvalid) (Syntax: '(y, z, w)')
NaturalType: (System.Int32 y, System.Int32 z, System.Int32 w)
Elements(3):
ILocalReferenceOperation: y (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'y')
ILocalReferenceOperation: z (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'z')
ILocalReferenceOperation: w (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'w')
Right:
IInvocationOperation (Pair<System.Int32, (System.Int32, System.Int32)> Pair.Create<System.Int32, (System.Int32, System.Int32)>(System.Int32 item1, (System.Int32, System.Int32) item2)) (OperationKind.Invocation, Type: Pair<System.Int32, (System.Int32, System.Int32)>, IsInvalid) (Syntax: 'Pair.Create ... , (43, 44))')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item1) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '42')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item2) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: '(43, 44)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(43, 44)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 43, IsInvalid) (Syntax: '43')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 44, IsInvalid) (Syntax: '44')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// /*<bind>*/(x, (y, z, w)) = Pair.Create(42, (43, 44))/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(x, (y, z, w)) = Pair.Create(42, (43, 44))").WithArguments("2", "3").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeconstructionTooFewElements()
{
string source = @"
class C
{
static void Main()
{
for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
}
}
" + commonSource;
string expectedOperationTree = @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: '(var(x, y)) ... reate(1, 2)')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x, y)')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'y')
Children(0)
Right:
IInvocationOperation (Pair<System.Int32, System.Int32> Pair.Create<System.Int32, System.Int32>(System.Int32 item1, System.Int32 item2)) (OperationKind.Invocation, Type: Pair<System.Int32, System.Int32>) (Syntax: 'Pair.Create(1, 2)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item1) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
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)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: item2) (OperationKind.Argument, Type: null) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'var' does not exist in the current context
// for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 25),
// CS0103: The name 'x' does not exist in the current context
// for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x").WithArguments("x").WithLocation(6, 29),
// CS0103: The name 'y' does not exist in the current context
// for (/*<bind>*/(var(x, y)) = Pair.Create(1, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "y").WithArguments("y").WithLocation(6, 32)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void DeconstructionDeclarationInCSharp6()
{
string source = @"
class C
{
static void Main()
{
var (x1, x2) = Pair.Create(1, 2);
(int x3, int x4) = Pair.Create(1, 2);
foreach ((int x5, var (x6, x7)) in new[] { Pair.Create(1, Pair.Create(2, 3)) }) { }
for ((int x8, var (x9, x10)) = Pair.Create(1, Pair.Create(2, 3)); ; ) { }
}
}
" + commonSource;
var comp = CreateCompilation(source, parseOptions: TestOptions.Regular6);
comp.VerifyDiagnostics(
// (6,13): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// var (x1, x2) = Pair.Create(1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(x1, x2)").WithArguments("tuples", "7.0").WithLocation(6, 13),
// (7,9): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// (int x3, int x4) = Pair.Create(1, 2);
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int x3, int x4)").WithArguments("tuples", "7.0").WithLocation(7, 9),
// (8,18): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// foreach ((int x5, var (x6, x7)) in new[] { Pair.Create(1, Pair.Create(2, 3)) }) { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int x5, var (x6, x7))").WithArguments("tuples", "7.0").WithLocation(8, 18),
// (9,14): error CS8059: Feature 'tuples' is not available in C# 6. Please use language version 7.0 or greater.
// for ((int x8, var (x9, x10)) = Pair.Create(1, Pair.Create(2, 3)); ; ) { }
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion6, "(int x8, var (x9, x10))").WithArguments("tuples", "7.0").WithLocation(9, 14)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclareLocalTwice()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x1) = (1, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'var (x1, x1) = (1, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'var (x1, x1)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(x1, x1)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0128: A local variable or function named 'x1' is already defined in this scope
// /*<bind>*/var (x1, x1) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(6, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclareLocalTwice2()
{
string source = @"
class C
{
static void Main()
{
string x1 = null;
/*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
System.Console.WriteLine(x1);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0128: A local variable or function named 'x1' is already defined in this scope
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x1").WithArguments("x1").WithLocation(7, 24)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void VarMethodMissing()
{
string source = @"
class C
{
static void Main()
{
int x1 = 1;
int x2 = 1;
/*<bind>*/var(x1, x2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x1, x2)')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'var' does not exist in the current context
// /*<bind>*/var(x1, x2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<InvocationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UseBeforeDeclared()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
}
static (int, int) M(int a) { return (1, 2); }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(int x1, int x2) = M(x1)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IInvocationOperation ((System.Int32, System.Int32) C.M(System.Int32 a)) (OperationKind.Invocation, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: 'M(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0165: Use of unassigned local variable 'x1'
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(6, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclareWithVoidType()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
}
static void M(int a) { }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(int x1, int x2) = M(x1)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IInvocationOperation (void C.M(System.Int32 a)) (OperationKind.Invocation, Type: System.Void, IsInvalid) (Syntax: 'M(x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
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)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1061: 'void' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'void' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M(x1)").WithArguments("void", "Deconstruct").WithLocation(6, 38),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'void', with 2 out parameters and a void return type.
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "M(x1)").WithArguments("void", "2").WithLocation(6, 38),
// CS0165: Use of unassigned local variable 'x1'
// /*<bind>*/(int x1, int x2) = M(x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(6, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void UseBeforeDeclared2()
{
string source = @"
class C
{
static void Main()
{
System.Console.WriteLine(x1);
/*<bind>*/(int x1, int x2) = (1, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, in ... 2) = (1, 2)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x1' before it is declared
// System.Console.WriteLine(x1);
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 34)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NullAssignmentInDeclaration()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(int x1, int x2) = null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(int x1, int x2) = null')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2)) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/(int x1, int x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void NullAssignmentInVarDeclaration()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = null/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: 'var (x1, x2) = null')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/var (x1, x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(6, 34),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// /*<bind>*/var (x1, x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 24),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/var (x1, x2) = null/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypelessDeclaration()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (1, null)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: 'var (x1, x2) = (1, null)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(1, null)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// /*<bind>*/var (x1, x2) = (1, null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 24),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/var (x1, x2) = (1, null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithMultipleAmbiguousVars()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, (byte x2, var x3), var x4) = (null, (2, null), null)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(string x1, ... ull), null)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, (System.Byte x2, var x3), var x4), IsInvalid) (Syntax: '(string x1, ... 3), var x4)')
NaturalType: (System.String x1, (System.Byte x2, var x3), var x4)
Elements(3):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String) (Syntax: 'x1')
ITupleOperation (OperationKind.Tuple, Type: (System.Byte x2, var x3), IsInvalid) (Syntax: '(byte x2, var x3)')
NaturalType: (System.Byte x2, var x3)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Byte) (Syntax: 'byte x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Byte) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x4')
ILocalReferenceOperation: x4 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x4')
Right:
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(null, (2, null), null)')
NaturalType: null
Elements(3):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(2, null)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x3'.
// /*<bind>*/(string x1, (byte x2, var x3), var x4) = (null, (2, null), null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x3").WithArguments("x3").WithLocation(6, 45),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x4'.
// /*<bind>*/(string x1, (byte x2, var x3), var x4) = (null, (2, null), null)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x4").WithArguments("x4").WithLocation(6, 54)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyLeftNestings()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/((string x1, byte x2, var x3), int x4) = (null, 4)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '((string x1 ... = (null, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((System.String x1, System.Byte x2, var x3), System.Int32 x4), IsInvalid) (Syntax: '((string x1 ... 3), int x4)')
NaturalType: ((System.String x1, System.Byte x2, var x3), System.Int32 x4)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, System.Byte x2, var x3), IsInvalid) (Syntax: '(string x1, ... x2, var x3)')
NaturalType: (System.String x1, System.Byte x2, var x3)
Elements(3):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Byte) (Syntax: 'byte x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Byte) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x3')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x4')
ILocalReferenceOperation: x4 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x4')
Right:
ITupleOperation (OperationKind.Tuple, Type: null, IsInvalid) (Syntax: '(null, 4)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// /*<bind>*/((string x1, byte x2, var x3), int x4) = (null, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(6, 61),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x3'.
// /*<bind>*/((string x1, byte x2, var x3), int x4) = (null, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x3").WithArguments("x3").WithLocation(6, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyRightNestings()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, var x2) = (null, (null, 2))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: System.Void, IsInvalid) (Syntax: '(string x1, ... (null, 2))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, var x2), IsInvalid) (Syntax: '(string x1, var x2)')
NaturalType: (System.String x1, var x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var, IsInvalid) (Syntax: 'var x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(null, (null, 2))')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ITupleOperation (OperationKind.Tuple, Type: null) (Syntax: '(null, 2)')
NaturalType: null
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/(string x1, var x2) = (null, (null, 2))/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyLeftVariables()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, var x2, int x3) = (null, ""hello"")/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(string x1, ... l, ""hello"")')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, System.String x2, System.Int32 x3), IsInvalid) (Syntax: '(string x1, ... x2, int x3)')
NaturalType: (System.String x1, System.String x2, System.Int32 x3)
Elements(3):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'var x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.String, System.String), IsInvalid) (Syntax: '(null, ""hello"")')
NaturalType: null
Elements(2):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"", IsInvalid) (Syntax: '""hello""')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables.
// /*<bind>*/(string x1, var x2, int x3) = (null, "hello")/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, @"(string x1, var x2, int x3) = (null, ""hello"")").WithArguments("2", "3").WithLocation(6, 19)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void TypeMergingWithTooManyRightElements()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(string x1, var y1) = (null, ""hello"", 3)/*</bind>*/;
(string x2, var y2) = (null, ""hello"", null);
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(string x1, ... ""hello"", 3)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.String x1, System.String y1), IsInvalid) (Syntax: '(string x1, var y1)')
NaturalType: (System.String x1, System.String y1)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'string x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.String, IsInvalid) (Syntax: 'var y1')
ILocalReferenceOperation: y1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.String, IsInvalid) (Syntax: 'y1')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.String, System.String, System.Int32), IsInvalid) (Syntax: '(null, ""hello"", 3)')
NaturalType: null
Elements(3):
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.String, Constant: null, IsInvalid, IsImplicit) (Syntax: 'null')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: ""hello"", IsInvalid) (Syntax: '""hello""')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '3' elements into '2' variables.
// /*<bind>*/(string x1, var y1) = (null, "hello", 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, @"(string x1, var y1) = (null, ""hello"", 3)").WithArguments("3", "2").WithLocation(6, 19),
// CS8131: Deconstruct assignment requires an expression with a type on the right-hand-side.
// (string x2, var y2) = (null, "hello", null);
Diagnostic(ErrorCode.ERR_DeconstructRequiresExpression, "null").WithLocation(7, 47),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y2'.
// (string x2, var y2) = (null, "hello", null);
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y2").WithArguments("y2").WithLocation(7, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationVarFormWithActualVarType()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
}
}
class var { }
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (var, var), IsInvalid, IsImplicit) (Syntax: '(1, 2)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x1, x2)").WithLocation(6, 23),
// CS0029: Cannot implicitly convert type 'int' to 'var'
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "var").WithLocation(6, 35),
// CS0029: Cannot implicitly convert type 'int' to 'var'
// /*<bind>*/var (x1, x2) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "var").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationVarFormWithAliasedVarType()
{
string source = @"
using var = D;
class C
{
static void Main()
{
/*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
}
}
class D
{
public override string ToString() { return ""var""; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (D x3, D x4), IsInvalid) (Syntax: 'var (x3, x4) = (3, 4)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (D x3, D x4), IsInvalid) (Syntax: 'var (x3, x4)')
ITupleOperation (OperationKind.Tuple, Type: (D x3, D x4), IsInvalid) (Syntax: '(x3, x4)')
NaturalType: (D x3, D x4)
Elements(2):
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: D, IsInvalid) (Syntax: 'x3')
ILocalReferenceOperation: x4 (IsDeclaration: True) (OperationKind.LocalReference, Type: D, IsInvalid) (Syntax: 'x4')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (D, D), IsInvalid, IsImplicit) (Syntax: '(3, 4)')
Conversion: CommonConversion (Exists: False, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32), IsInvalid) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4, IsInvalid) (Syntax: '4')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8136: Deconstruction 'var (...)' form disallows a specific type for 'var'.
// /*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "(x3, x4)").WithLocation(7, 23),
// CS0029: Cannot implicitly convert type 'int' to 'D'
// /*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "3").WithArguments("int", "D").WithLocation(7, 35),
// CS0029: Cannot implicitly convert type 'int' to 'D'
// /*<bind>*/var (x3, x4) = (3, 4)/*</bind>*/;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "4").WithArguments("int", "D").WithLocation(7, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithWrongCardinality()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: '(var (x1, x ... = (1, 2, 3)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((var x1, var x2), System.Int32 x3), IsInvalid) (Syntax: '(var (x1, x2), var x3)')
NaturalType: ((var x1, var x2), System.Int32 x3)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'var x3')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x3')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32, System.Int32), IsInvalid) (Syntax: '(1, 2, 3)')
NaturalType: (System.Int32, System.Int32, System.Int32)
Elements(3):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsInvalid) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2, IsInvalid) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3, IsInvalid) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8132: Cannot deconstruct a tuple of '3' elements into '2' variables.
// /*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(var (x1, x2), var x3) = (1, 2, 3)").WithArguments("3", "2").WithLocation(6, 19),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// /*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 25),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// /*<bind>*/(var (x1, x2), var x3) = (1, 2, 3)/*</bind>*/;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 29)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithCircularity1()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, var x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, x1)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x1, var x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, var x2)) (Syntax: '(x1, x2)')
NaturalType: (System.Int32 x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, var), IsInvalid, IsImplicit) (Syntax: '(1, x1)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, var x1), IsInvalid) (Syntax: '(1, x1)')
NaturalType: (System.Int32, var x1)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x1' before it is declared
// /*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 38)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithCircularity2()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (var x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2) = (x2, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, System.Int32 x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, System.Int32 x2)) (Syntax: '(x1, x2)')
NaturalType: (var x1, System.Int32 x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (var, System.Int32), IsInvalid, IsImplicit) (Syntax: '(x2, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (var x2, System.Int32), IsInvalid) (Syntax: '(x2, 2)')
NaturalType: (var x2, System.Int32)
Elements(2):
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x2' before it is declared
// /*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(6, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningVarInvocation()
{
string source = @"
class C
{
static int i;
static void Main()
{
int x = 0, y = 0;
/*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
System.Console.WriteLine(i);
}
static ref int var(int a, int b) { return ref i; }
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ?, IsInvalid) (Syntax: 'var (x, y) = 42')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x, var y), IsInvalid) (Syntax: 'var (x, y)')
ITupleOperation (OperationKind.Tuple, Type: (var x, var y), IsInvalid) (Syntax: '(x, y)')
NaturalType: (var x, var y)
Elements(2):
ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x')
ILocalReferenceOperation: y (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 42, IsInvalid) (Syntax: '42')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0128: A local variable or function named 'x' is already defined in this scope
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(9, 24),
// CS0128: A local variable or function named 'y' is already defined in this scope
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(9, 27),
// CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("int", "Deconstruct").WithLocation(9, 32),
// CS8129: No suitable Deconstruct instance or extension method was found for type 'int', with 2 out parameters and a void return type.
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "42").WithArguments("int", "2").WithLocation(9, 32),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'.
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(9, 24),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'.
// /*<bind>*/var (x, y) = 42/*</bind>*/; // parsed as deconstruction
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(9, 27),
// CS0219: The variable 'x' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13),
// CS0219: The variable 'y' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(8, 20)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/12468"), CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12468, "https://github.com/dotnet/roslyn/issues/12468")]
public void RefReturningVarInvocation2()
{
string source = @"
class C
{
static int i = 0;
static void Main()
{
int x = 0, y = 0;
@var(x, y) = 42; // parsed as invocation
System.Console.Write(i + "" "");
(var(x, y)) = 43; // parsed as invocation
System.Console.Write(i + "" "");
(var(x, y) = 44); // parsed as invocation
System.Console.Write(i);
}
static ref int var(int a, int b) { return ref i; }
}
";
// The correct expectation is for the code to compile and execute
//var comp = CompileAndVerify(source, expectedOutput: "42 43 44");
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (11,9): error CS8134: Deconstruction must contain at least two variables.
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_DeconstructTooFewElements, "(var(x, y)) = 43").WithLocation(11, 9),
// (13,20): error CS1026: ) expected
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_CloseParenExpected, "=").WithLocation(13, 20),
// (13,24): error CS1002: ; expected
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(13, 24),
// (13,24): error CS1513: } expected
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(13, 24),
// (9,14): error CS0128: A local variable named 'x' is already defined in this scope
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(9, 14),
// (9,9): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(9, 9),
// (9,14): error CS8136: Deconstruction `var (...)` form disallows a specific type for 'var'.
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "x").WithLocation(9, 14),
// (9,17): error CS0128: A local variable named 'y' is already defined in this scope
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(9, 17),
// (9,9): error CS0246: The type or namespace name 'var' could not be found (are you missing a using directive or an assembly reference?)
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "@var").WithArguments("var").WithLocation(9, 9),
// (9,17): error CS8136: Deconstruction `var (...)` form disallows a specific type for 'var'.
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_DeconstructionVarFormDisallowsSpecificType, "y").WithLocation(9, 17),
// (9,22): error CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "42").WithArguments("int", "Deconstruct").WithLocation(9, 22),
// (9,22): error CS8129: No Deconstruct instance or extension method was found for type 'int', with 2 out parameters.
// @var(x, y) = 42; // parsed as invocation
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "42").WithArguments("int", "2").WithLocation(9, 22),
// (11,14): error CS0128: A local variable named 'x' is already defined in this scope
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(11, 14),
// (11,17): error CS0128: A local variable named 'y' is already defined in this scope
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(11, 17),
// (11,23): error CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "43").WithArguments("int", "Deconstruct").WithLocation(11, 23),
// (11,23): error CS8129: No Deconstruct instance or extension method was found for type 'int', with 1 out parameters.
// (var(x, y)) = 43; // parsed as invocation
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "43").WithArguments("int", "1").WithLocation(11, 23),
// (13,14): error CS0128: A local variable named 'x' is already defined in this scope
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "x").WithArguments("x").WithLocation(13, 14),
// (13,17): error CS0128: A local variable named 'y' is already defined in this scope
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_LocalDuplicate, "y").WithArguments("y").WithLocation(13, 17),
// (13,22): error CS1061: 'int' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?)
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "44").WithArguments("int", "Deconstruct").WithLocation(13, 22),
// (13,22): error CS8129: No Deconstruct instance or extension method was found for type 'int', with 1 out parameters.
// (var(x, y) = 44); // parsed as invocation
Diagnostic(ErrorCode.ERR_MissingDeconstruct, "44").WithArguments("int", "1").WithLocation(13, 22),
// (8,13): warning CS0219: The variable 'x' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(8, 13),
// (8,20): warning CS0219: The variable 'y' is assigned but its value is never used
// int x = 0, y = 0;
Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(8, 20)
);
}
[Fact, CompilerTrait(CompilerFeature.RefLocalsReturns)]
[WorkItem(12283, "https://github.com/dotnet/roslyn/issues/12283")]
public void RefReturningInvocation()
{
string source = @"
class C
{
static int i;
static void Main()
{
int x = 0, y = 0;
M(x, y) = 42;
System.Console.WriteLine(i);
}
static ref int M(int a, int b) { return ref i; }
}
";
var comp = CompileAndVerify(source, expectedOutput: "42");
comp.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DeclarationWithTypeInsideVarForm()
{
string source = @"
class C
{
static void Main()
{
var(int x1, x2) = (1, 2);
var(var x3, x4) = (1, 2);
/*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: ?, IsInvalid) (Syntax: 'var(x5, var ... (1, (2, 3))')
Left:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x5, var(x6, x7))')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x5')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var(x6, x7)')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'var')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x6')
Children(0)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x7')
Children(0)
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'int'
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 13),
// CS1003: Syntax error, ',' expected
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x1").WithArguments(",", "").WithLocation(6, 17),
// CS1003: Syntax error, ',' expected
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_SyntaxError, "x3").WithArguments(",", "").WithLocation(7, 17),
// CS8199: The syntax 'var (...)' as an lvalue is reserved.
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(int x1, x2)").WithLocation(6, 9),
// CS0103: The name 'var' does not exist in the current context
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9),
// CS0103: The name 'x1' does not exist in the current context
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 17),
// CS0103: The name 'x2' does not exist in the current context
// var(int x1, x2) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(6, 21),
// CS8199: The syntax 'var (...)' as an lvalue is reserved.
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(var x3, x4)").WithLocation(7, 9),
// CS0103: The name 'var' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 9),
// CS0103: The name 'var' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 13),
// CS0103: The name 'x3' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x3").WithArguments("x3").WithLocation(7, 17),
// CS0103: The name 'x4' does not exist in the current context
// var(var x3, x4) = (1, 2);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x4").WithArguments("x4").WithLocation(7, 21),
// CS8199: The syntax 'var (...)' as an lvalue is reserved.
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_VarInvocationLvalueReserved, "var(x5, var(x6, x7))").WithLocation(8, 19),
// CS0103: The name 'var' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 19),
// CS0103: The name 'x5' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x5").WithArguments("x5").WithLocation(8, 23),
// CS0103: The name 'var' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(8, 27),
// CS0103: The name 'x6' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x6").WithArguments("x6").WithLocation(8, 31),
// CS0103: The name 'x7' does not exist in the current context
// /*<bind>*/var(x5, var(x6, x7)) = (1, (2, 3))/*</bind>*/;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x7").WithArguments("x7").WithLocation(8, 35)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForWithCircularity1()
{
string source = @"
class C
{
static void Main()
{
for (/*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/; ;) { }
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x1, var x2), IsInvalid) (Syntax: 'var (x1, x2) = (1, x1)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x1, var x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, var x2)) (Syntax: '(x1, x2)')
NaturalType: (System.Int32 x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, var), IsInvalid, IsImplicit) (Syntax: '(1, x1)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, var x1), IsInvalid) (Syntax: '(1, x1)')
NaturalType: (System.Int32, var x1)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILocalReferenceOperation: x1 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x1' before it is declared
// for (/*<bind>*/var (x1, x2) = (1, x1)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 43)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForWithCircularity2()
{
string source = @"
class C
{
static void Main()
{
for (/*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/; ;) { }
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (var x1, System.Int32 x2), IsInvalid) (Syntax: 'var (x1, x2) = (x2, 2)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, System.Int32 x2)) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, System.Int32 x2)) (Syntax: '(x1, x2)')
NaturalType: (var x1, System.Int32 x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (var, System.Int32), IsInvalid, IsImplicit) (Syntax: '(x2, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (var x2, System.Int32), IsInvalid) (Syntax: '(x2, 2)')
NaturalType: (var x2, System.Int32)
Elements(2):
ILocalReferenceOperation: x2 (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0841: Cannot use local variable 'x2' before it is declared
// for (/*<bind>*/var (x1, x2) = (x2, 2)/*</bind>*/; ;) { }
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(6, 40)
};
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachNameConflict()
{
string source = @"
class C
{
static void Main()
{
int x1 = 1;
/*<bind>*/foreach ((int x1, int x2) in M()) { }/*</bind>*/
System.Console.Write(x1);
}
static (int, int)[] M() { return new[] { (1, 2) }; }
}
";
string expectedOperationTree = @"
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'foreach ((i ... in M()) { }')
Locals: Local_1: System.Int32 x1
Local_2: System.Int32 x2
LoopControlVariable:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'M()')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ((System.Int32, System.Int32)[] C.M()) (OperationKind.Invocation, Type: (System.Int32, System.Int32)[]) (Syntax: 'M()')
Instance Receiver:
null
Arguments(0)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
NextVariables(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// /*<bind>*/foreach ((int x1, int x2) in M()) { }/*</bind>*/
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(7, 33)
};
VerifyOperationTreeAndDiagnosticsForTest<ForEachVariableStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachNameConflict2()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/foreach ((int x1, int x2) in M(out int x1)) { }/*</bind>*/
}
static (int, int)[] M(out int a) { a = 1; return new[] { (1, 2) }; }
}
";
string expectedOperationTree = @"
IForEachLoopOperation (LoopKind.ForEach, Continue Label Id: 0, Exit Label Id: 1) (OperationKind.Loop, Type: null, IsInvalid) (Syntax: 'foreach ((i ... nt x1)) { }')
Locals: Local_1: System.Int32 x1
Local_2: System.Int32 x2
LoopControlVariable:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, System.Int32 x2), IsInvalid) (Syntax: '(int x1, int x2)')
NaturalType: (System.Int32 x1, System.Int32 x2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32, IsInvalid) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsInvalid) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x2')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
Collection:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'M(out int x1)')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IInvocationOperation ((System.Int32, System.Int32)[] C.M(out System.Int32 a)) (OperationKind.Invocation, Type: (System.Int32, System.Int32)[]) (Syntax: 'M(out int x1)')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: a) (OperationKind.Argument, Type: null) (Syntax: 'out int x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
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)
Body:
IBlockOperation (0 statements) (OperationKind.Block, Type: null) (Syntax: '{ }')
NextVariables(0)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// /*<bind>*/foreach ((int x1, int x2) in M(out int x1)) { }/*</bind>*/
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(6, 33)
};
VerifyOperationTreeAndDiagnosticsForTest<ForEachVariableStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void ForEachNameConflict3()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, int x2) in M())
{
int x1 = 1;
System.Console.Write(x1);
}
}
static (int, int)[] M() { return new[] { (1, 2) }; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (8,17): error CS0136: A local or parameter named 'x1' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// int x1 = 1;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "x1").WithArguments("x1").WithLocation(8, 17)
);
}
[Fact]
public void ForEachUseBeforeDeclared()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, int x2) in M(x1)) { }
}
static (int, int)[] M(int a) { return new[] { (1, 2) }; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,40): error CS0103: The name 'x1' does not exist in the current context
// foreach ((int x1, int x2) in M(x1))
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 40)
);
}
[Fact]
public void ForEachUseOutsideScope()
{
string source = @"
class C
{
static void Main()
{
foreach ((int x1, int x2) in M()) { }
System.Console.Write(x1);
}
static (int, int)[] M() { return new[] { (1, 2) }; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (7,30): error CS0103: The name 'x1' does not exist in the current context
// System.Console.Write(x1);
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(7, 30)
);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachNoIEnumerable()
{
string source = @"
class C
{
static void Main()
{
foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
{
System.Console.WriteLine(x1 + "" "" + x2);
}
}
}
";
string expectedOperationTree = @"
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (var x1, var x2), IsInvalid) (Syntax: 'var (x1, x2)')
ITupleOperation (OperationKind.Tuple, Type: (var x1, var x2), IsInvalid) (Syntax: '(x1, x2)')
NaturalType: (var x1, var x2)
Elements(2):
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x1')
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var, IsInvalid) (Syntax: 'x2')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1579: foreach statement cannot operate on variables of type 'int' because 'int' does not contain a public definition for 'GetEnumerator'
// foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
Diagnostic(ErrorCode.ERR_ForEachMissingMember, "1").WithArguments("int", "GetEnumerator").WithLocation(6, 55),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 33),
// CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// foreach (/*<bind>*/var (x1, x2)/*</bind>*/ in 1)
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 37)
};
VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void ForEachIterationVariablesAreReadonly()
{
string source = @"
class C
{
static void Main()
{
foreach (/*<bind>*/(int x1, var (x2, x3))/*</bind>*/ in new[] { (1, (1, 1)) })
{
x1 = 1;
x2 = 2;
x3 = 3;
}
}
}
";
string expectedOperationTree = @"
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x1, (System.Int32 x2, System.Int32 x3))) (Syntax: '(int x1, var (x2, x3))')
NaturalType: (System.Int32 x1, (System.Int32 x2, System.Int32 x3))
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int x1')
ILocalReferenceOperation: x1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 x2, System.Int32 x3)) (Syntax: 'var (x2, x3)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x2, System.Int32 x3)) (Syntax: '(x2, x3)')
NaturalType: (System.Int32 x2, System.Int32 x3)
Elements(2):
ILocalReferenceOperation: x2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x2')
ILocalReferenceOperation: x3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1656: Cannot assign to 'x1' because it is a 'foreach iteration variable'
// x1 = 1;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x1").WithArguments("x1", "foreach iteration variable").WithLocation(8, 13),
// CS1656: Cannot assign to 'x2' because it is a 'foreach iteration variable'
// x2 = 2;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x2").WithArguments("x2", "foreach iteration variable").WithLocation(9, 13),
// CS1656: Cannot assign to 'x3' because it is a 'foreach iteration variable'
// x3 = 3;
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x3").WithArguments("x3", "foreach iteration variable").WithLocation(10, 13)
};
VerifyOperationTreeAndDiagnosticsForTest<TupleExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void ForEachScoping()
{
string source = @"
class C
{
static void Main()
{
foreach (var (x1, x2) in M(x1)) { }
}
static (int, int) M(int i) { return (1, 2); }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,36): error CS0103: The name 'x1' does not exist in the current context
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 36),
// (6,34): error CS1579: foreach statement cannot operate on variables of type '(int, int)' because '(int, int)' does not contain a public instance or extension definition for 'GetEnumerator'
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_ForEachMissingMember, "M(x1)").WithArguments("(int, int)", "GetEnumerator").WithLocation(6, 34),
// (6,23): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x1'.
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x1").WithArguments("x1").WithLocation(6, 23),
// (6,27): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x2'.
// foreach (var (x1, x2) in M(x1)) { }
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x2").WithArguments("x2").WithLocation(6, 27)
);
}
[Fact]
public void AssignmentDataFlow()
{
string source = @"
class C
{
static void Main()
{
int x, y;
(x, y) = new C(); // x and y are assigned here, so no complaints on usage of un-initialized locals on the line below
System.Console.WriteLine(x + "" "" + y);
}
public void Deconstruct(out int a, out int b)
{
a = 1;
b = 2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void GetTypeInfoForTupleLiteral()
{
var source = @"
class C
{
static void Main()
{
var x1 = (1, 2);
var (x2, x3) = (1, 2);
System.Console.Write($""{x1} {x2} {x3}"");
}
}
";
Action<ModuleSymbol> validator = module =>
{
var sourceModule = (SourceModuleSymbol)module;
var compilation = sourceModule.DeclaringCompilation;
var tree = compilation.SyntaxTrees.First();
var model = compilation.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var literal1 = nodes.OfType<TupleExpressionSyntax>().First();
Assert.Equal("(int, int)", model.GetTypeInfo(literal1).Type.ToDisplayString());
var literal2 = nodes.OfType<TupleExpressionSyntax>().Skip(1).First();
Assert.Equal("(int, int)", model.GetTypeInfo(literal2).Type.ToDisplayString());
};
var verifier = CompileAndVerify(source, sourceSymbolValidator: validator);
verifier.VerifyDiagnostics();
}
[Fact]
public void DeclarationWithCircularity3()
{
string source = @"
class C
{
static void Main()
{
var (x1, x2) = (M(out x2), M(out x1));
}
static T M<T>(out T x) { x = default(T); return x; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,31): error CS0841: Cannot use local variable 'x2' before it is declared
// var (x1, x2) = (M(out x2), M(out x1));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x2").WithArguments("x2").WithLocation(6, 31),
// (6,42): error CS0841: Cannot use local variable 'x1' before it is declared
// var (x1, x2) = (M(out x2), M(out x1));
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x1").WithArguments("x1").WithLocation(6, 42)
);
}
[Fact, WorkItem(13081, "https://github.com/dotnet/roslyn/issues/13081")]
public void GettingDiagnosticsWhenValueTupleIsMissing()
{
var source = @"
class C1
{
static void Test(int arg1, (byte, byte) arg2)
{
foreach ((int, int) e in new (int, int)[10])
{
}
}
}
";
var comp = CreateCompilationWithMscorlib40(source);
comp.VerifyDiagnostics(
// (4,32): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// static void Test(int arg1, (byte, byte) arg2)
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(byte, byte)").WithArguments("System.ValueTuple`2").WithLocation(4, 32),
// (6,38): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// foreach ((int, int) e in new (int, int)[10])
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(6, 38),
// (6,18): error CS8179: Predefined type 'System.ValueTuple`2' is not defined or imported
// foreach ((int, int) e in new (int, int)[10])
Diagnostic(ErrorCode.ERR_PredefinedValueTupleTypeNotFound, "(int, int)").WithArguments("System.ValueTuple`2").WithLocation(6, 18)
);
// no crash
}
[Fact]
public void DeconstructionMayBeEmbedded()
{
var source = @"
class C1
{
void M()
{
if (true)
var (x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// this is no longer considered a declaration statement,
// but rather is an assignment expression. So no error.
);
}
[Fact]
public void AssignmentExpressionCanBeUsedInEmbeddedStatement()
{
var source = @"
class C1
{
void M()
{
int x, y;
if (true)
(x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
}
[Fact]
public void DeconstructObsoleteWarning()
{
var source = @"
class C
{
void M()
{
(int y1, int y2) = new C();
}
[System.Obsolete()]
void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,27): warning CS0612: 'C.Deconstruct(out int, out int)' is obsolete
// (int y1, int y2) = new C();
Diagnostic(ErrorCode.WRN_DeprecatedSymbol, "new C()").WithArguments("C.Deconstruct(out int, out int)").WithLocation(6, 27)
);
}
[Fact]
public void DeconstructObsoleteError()
{
var source = @"
class C
{
void M()
{
(int y1, int y2) = new C();
}
[System.Obsolete(""Deprecated"", error: true)]
void Deconstruct(out int x1, out int x2) { x1 = 1; x2 = 2; }
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,27): error CS0619: 'C.Deconstruct(out int, out int)' is obsolete: 'Deprecated'
// (int y1, int y2) = new C();
Diagnostic(ErrorCode.ERR_DeprecatedSymbolStr, "new C()").WithArguments("C.Deconstruct(out int, out int)", "Deprecated").WithLocation(6, 27)
);
}
[Fact]
public void DeconstructionLocalsDeclaredNotUsed()
{
// Check that there are no *use sites* within this code for local variables.
// They are not declared. So they should not be returned
// by SemanticModel.GetSymbolInfo. Similarly, check that all designation syntax
// forms declare deconstruction locals.
string source = @"
class Program
{
static void Main()
{
var (x1, y1) = (1, 2);
(var x2, var y2) = (1, 2);
}
static void M((int, int) t)
{
var (x3, y3) = t;
(var x4, var y4) = t;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics();
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree, ignoreAccessibility: false);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
foreach (var node in nodes)
{
var si = model.GetSymbolInfo(node);
var symbol = si.Symbol;
if ((object)symbol != null)
{
if (node is DeclarationExpressionSyntax)
{
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal(LocalDeclarationKind.DeconstructionVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
}
else
{
Assert.NotEqual(SymbolKind.Local, symbol.Kind);
}
}
symbol = model.GetDeclaredSymbol(node);
if ((object)symbol != null)
{
if (node is SingleVariableDesignationSyntax)
{
Assert.Equal(SymbolKind.Local, symbol.Kind);
Assert.Equal(LocalDeclarationKind.DeconstructionVariable, symbol.GetSymbol<LocalSymbol>().DeclarationKind);
}
else
{
Assert.NotEqual(SymbolKind.Local, symbol.Kind);
}
}
}
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(14287, "https://github.com/dotnet/roslyn/issues/14287")]
public void TupleDeconstructionStatementWithTypesCannotBeConst()
{
string source = @"
class C
{
static void Main()
{
/*<bind>*/const (int x, int y) = (1, 2);/*</bind>*/
}
}
";
string expectedOperationTree = @"
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null, IsInvalid) (Syntax: 'const (int ... ) = (1, 2);')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null, IsInvalid) (Syntax: '(int x, int y) = (1, 2)')
Declarators:
IVariableDeclaratorOperation (Symbol: (System.Int32 x, System.Int32 y) ) (OperationKind.VariableDeclarator, Type: null, IsInvalid) (Syntax: '= (1, 2)')
Initializer:
IVariableInitializerOperation (OperationKind.VariableInitializer, Type: null, IsInvalid) (Syntax: '= (1, 2)')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32 x, System.Int32 y), IsImplicit) (Syntax: '(1, 2)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Initializer:
null
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1001: Identifier expected
// const /*<bind>*/(int x, int y) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_IdentifierExpected, "=").WithLocation(6, 40),
// CS0283: The type '(int x, int y)' cannot be declared const
// const /*<bind>*/(int x, int y) = (1, 2)/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadConstType, "(int x, int y)").WithArguments("(int x, int y)").WithLocation(6, 25)
};
VerifyOperationTreeAndDiagnosticsForTest<LocalDeclarationStatementSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(14287, "https://github.com/dotnet/roslyn/issues/14287")]
public void TupleDeconstructionStatementWithoutTypesCannotBeConst()
{
string source = @"
class C
{
static void Main()
{
const var (x, y) = (1, 2);
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,9): error CS0106: The modifier 'const' is not valid for this item
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_BadMemberFlag, "const").WithArguments("const").WithLocation(6, 9),
// (6,19): error CS1001: Identifier expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, "(").WithLocation(6, 19),
// (6,21): error CS1001: Identifier expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ",").WithLocation(6, 21),
// (6,24): error CS1001: Identifier expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(6, 24),
// (6,26): error CS1002: ; expected
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SemicolonExpected, "=").WithLocation(6, 26),
// (6,26): error CS1525: Invalid expression term '='
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(6, 26),
// (6,19): error CS8112: '(x, y)' is a local function and must therefore always have a body.
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_LocalFunctionMissingBody, "").WithArguments("(x, y)").WithLocation(6, 19),
// (6,20): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?)
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(6, 20),
// (6,23): error CS0246: The type or namespace name 'y' could not be found (are you missing a using directive or an assembly reference?)
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "y").WithArguments("y").WithLocation(6, 23),
// (6,15): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// const var (x, y) = (1, 2);
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(6, 15)
);
}
[Fact, WorkItem(15934, "https://github.com/dotnet/roslyn/issues/15934")]
public void PointerTypeInDeconstruction()
{
string source = @"
unsafe class C
{
static void Main(C c)
{
(int* x1, int y1) = c;
(var* x2, int y2) = c;
(int*[] x3, int y3) = c;
(var*[] x4, int y4) = c;
}
public void Deconstruct(out dynamic x, out dynamic y)
{
x = y = null;
}
}
";
var comp = CreateCompilationWithMscorlib40AndSystemCore(source,
references: new[] { ValueTupleRef, SystemRuntimeFacadeRef },
options: TestOptions.UnsafeDebugDll,
parseOptions: TestOptions.RegularPreview);
// The precise diagnostics here are not important, and may be sensitive to parser
// adjustments. This is a test that we don't crash. The errors here are likely to
// change as we adjust the parser and semantic analysis of error cases.
comp.VerifyDiagnostics(
// (6,10): error CS1525: Invalid expression term 'int'
// (int* x1, int y1) = c;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "int").WithArguments("int").WithLocation(6, 10),
// (6,15): error CS0103: The name 'x1' does not exist in the current context
// (int* x1, int y1) = c;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x1").WithArguments("x1").WithLocation(6, 15),
// (6,19): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (int* x1, int y1) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y1").WithArguments("dynamic", "int").WithLocation(6, 19),
// (7,10): error CS0103: The name 'var' does not exist in the current context
// (var* x2, int y2) = c;
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 10),
// (7,15): error CS0103: The name 'x2' does not exist in the current context
// (var* x2, int y2) = c;
Diagnostic(ErrorCode.ERR_NameNotInContext, "x2").WithArguments("x2").WithLocation(7, 15),
// (7,19): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (var* x2, int y2) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y2").WithArguments("dynamic", "int").WithLocation(7, 19),
// (8,10): error CS0266: Cannot implicitly convert type 'dynamic' to 'int*[]'. An explicit conversion exists (are you missing a cast?)
// (int*[] x3, int y3) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int*[] x3").WithArguments("dynamic", "int*[]").WithLocation(8, 10),
// (8,21): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (int*[] x3, int y3) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y3").WithArguments("dynamic", "int").WithLocation(8, 21),
// (9,10): error CS0825: The contextual keyword 'var' may only appear within a local variable declaration or in script code
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_TypeVarNotFound, "var").WithLocation(9, 10),
// (9,10): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('var')
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_ManagedAddr, "var*").WithArguments("var").WithLocation(9, 10),
// (9,10): error CS0266: Cannot implicitly convert type 'dynamic' to 'var*[]'. An explicit conversion exists (are you missing a cast?)
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "var*[] x4").WithArguments("dynamic", "var*[]").WithLocation(9, 10),
// (9,21): error CS0266: Cannot implicitly convert type 'dynamic' to 'int'. An explicit conversion exists (are you missing a cast?)
// (var*[] x4, int y4) = c;
Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "int y4").WithArguments("dynamic", "int").WithLocation(9, 21)
);
}
[Fact]
public void DeclarationInsideNameof()
{
string source = @"
class Program
{
static void Main()
{
string s = nameof((int x1, var x2) = (1, 2)).ToString();
string s1 = x1, s2 = x2;
}
}
";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (6,28): error CS8185: A declaration is not allowed in this context.
// string s = nameof((int x1, var x2) = (1, 2)).ToString();
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int x1").WithLocation(6, 28),
// (6,27): error CS8081: Expression does not have a name.
// string s = nameof((int x1, var x2) = (1, 2)).ToString();
Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "(int x1, var x2) = (1, 2)").WithLocation(6, 27),
// (7,21): error CS0029: Cannot implicitly convert type 'int' to 'string'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1").WithArguments("int", "string").WithLocation(7, 21),
// (7,30): error CS0029: Cannot implicitly convert type 'int' to 'string'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2").WithArguments("int", "string").WithLocation(7, 30),
// (7,21): error CS0165: Use of unassigned local variable 'x1'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(7, 21),
// (7,30): error CS0165: Use of unassigned local variable 'x2'
// string s1 = x1, s2 = x2;
Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(7, 30)
);
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(2, designations.Count());
var refs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<IdentifierNameSyntax>();
var x1 = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("x1", x1.Name);
Assert.Equal("System.Int32", ((ILocalSymbol)x1).Type.ToTestDisplayString());
Assert.Same(x1, model.GetSymbolInfo(refs.Where(r => r.Identifier.ValueText == "x1").Single()).Symbol);
var x2 = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("x2", x2.Name);
Assert.Equal("System.Int32", ((ILocalSymbol)x2).Type.ToTestDisplayString());
Assert.Same(x2, model.GetSymbolInfo(refs.Where(r => r.Identifier.ValueText == "x2").Single()).Symbol);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_01()
{
string source1 = @"
class C
{
static void Main()
{
(var (a,b), var c, int d);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)"),
// (6,21): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c"),
// (6,28): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(6, 28),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (a,b), var c, int d)").WithLocation(6, 9),
// (6,28): error CS0165: Use of unassigned local variable 'd'
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int d").WithArguments("d").WithLocation(6, 28)
);
StandAlone_01_VerifySemanticModel(comp1, LocalDeclarationKind.DeclarationExpressionVariable);
string source2 = @"
class C
{
static void Main()
{
(var (a,b), var c, int d) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_01_VerifySemanticModel(comp2, LocalDeclarationKind.DeconstructionVariable);
}
private static void StandAlone_01_VerifySemanticModel(CSharpCompilation comp, LocalDeclarationKind localDeclarationKind)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var a", a.ToTestDisplayString());
Assert.Equal(localDeclarationKind, a.GetSymbol<LocalSymbol>().DeclarationKind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var b", b.ToTestDisplayString());
Assert.Equal(localDeclarationKind, b.GetSymbol<LocalSymbol>().DeclarationKind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var c", c.ToTestDisplayString());
Assert.Equal(localDeclarationKind, c.GetSymbol<LocalSymbol>().DeclarationKind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 d", d.ToTestDisplayString());
Assert.Equal(localDeclarationKind, d.GetSymbol<LocalSymbol>().DeclarationKind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("((var a, var b), var c, System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_02()
{
string source1 = @"
(var (a,b), var c, int d);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,7): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a"),
// (2,9): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b"),
// (2,17): error CS7019: Type of 'c' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "c").WithArguments("c"),
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)"),
// (2,13): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c"),
// (2,20): error CS8185: A declaration is not allowed in this context.
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(2, 20),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (a,b), var c, int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (a,b), var c, int d)").WithLocation(2, 1)
);
StandAlone_02_VerifySemanticModel(comp1);
string source2 = @"
(var (a,b), var c, int d) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_02_VerifySemanticModel(comp2);
}
private static void StandAlone_02_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var Script.a", a.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, a.Kind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var Script.b", b.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, b.Kind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var Script.c", c.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, c.Kind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 Script.d", d.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, d.Kind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var Script.c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 Script.d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("((var a, var b), var c, System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_03()
{
string source1 = @"
class C
{
static void Main()
{
(var (_, _), var _, int _);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)"),
// (6,22): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _"),
// (6,29): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(6, 29),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (_, _), var _, int _)").WithLocation(6, 9)
);
StandAlone_03_VerifySemanticModel(comp1);
string source2 = @"
class C
{
static void Main()
{
(var (_, _), var _, int _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_03_VerifySemanticModel(comp2);
}
private static void StandAlone_03_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
int count = 0;
foreach (var designation in tree.GetCompilationUnitRoot().DescendantNodes().OfType<DiscardDesignationSyntax>())
{
Assert.Null(model.GetDeclaredSymbol(designation));
count++;
}
Assert.Equal(4, count);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (_, _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var, var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int _", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("((var, var), var, System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_04()
{
string source1 = @"
(var (_, _), var _, int _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)"),
// (2,14): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _"),
// (2,21): error CS8185: A declaration is not allowed in this context.
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(2, 21),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var (_, _), var _, int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var (_, _), var _, int _)").WithLocation(2, 1)
);
StandAlone_03_VerifySemanticModel(comp1);
string source2 = @"
(var (_, _), var _, int _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_03_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_05()
{
string source1 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (a,b), var c);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_05_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (a,b), var c) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_05_VerifySemanticModel(comp2);
}
private static void StandAlone_05_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(System.Int32 a, System.Int32 b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[0].Type).ToTestDisplayString());
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[1].Type).ToTestDisplayString());
}
[Fact]
[WorkItem(23651, "https://github.com/dotnet/roslyn/issues/23651")]
public void StandAlone_05_WithDuplicateNames()
{
string source1 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (a, a), var c);
}
}
";
var comp1 = CreateCompilation(source1);
var tree = comp1.SyntaxTrees.Single();
var model = comp1.GetSemanticModel(tree);
var nodes = tree.GetCompilationUnitRoot().DescendantNodes();
var aa = nodes.OfType<DeclarationExpressionSyntax>().ElementAt(0);
Assert.Equal("var (a, a)", aa.ToString());
var aaType = model.GetTypeInfo(aa).Type.GetSymbol();
Assert.True(aaType.TupleElementNames.IsDefault);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_06()
{
string source1 = @"
using var = System.Int32;
(var (a,b), var c);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_06_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
(var (a,b), var c) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_06_VerifySemanticModel(comp2);
}
private static void StandAlone_06_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(System.Int32 a, System.Int32 b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[0].Type).ToTestDisplayString());
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 Script.c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[1].Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_07()
{
string source1 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (_, _), var _);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_07_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
class C
{
static void Main()
{
(var (_, _), var _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_07_VerifySemanticModel(comp2);
}
private static void StandAlone_07_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var (_, _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(System.Int32, System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[0].Type).ToTestDisplayString());
Assert.Equal("var _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("var=System.Int32", model.GetAliasInfo(declarations[1].Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_08()
{
string source1 = @"
using var = System.Int32;
(var (_, _), var _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_07_VerifySemanticModel(comp1);
string source2 = @"
using var = System.Int32;
(var (_, _), var _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_07_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_09()
{
string source1 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (a,b), al c);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_09_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (a,b), al c) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_09_VerifySemanticModel(comp2);
}
private static void StandAlone_09_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
Assert.Equal("al c", declaration.ToString());
var typeInfo = model.GetTypeInfo(declaration);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration).IsIdentity);
Assert.Equal("System.Int32 c", model.GetSymbolInfo(declaration).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration.Type).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declaration.Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("al=System.Int32", model.GetAliasInfo(declaration.Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_10()
{
string source1 = @"
using al = System.Int32;
(al (a,b), al c);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_10_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
(al (a,b), al c) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_10_VerifySemanticModel(comp2);
}
private static void StandAlone_10_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
Assert.Equal("al c", declaration.ToString());
var typeInfo = model.GetTypeInfo(declaration);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration).IsIdentity);
Assert.Equal("System.Int32 Script.c", model.GetSymbolInfo(declaration).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declaration.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration.Type).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declaration.Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("al=System.Int32", model.GetAliasInfo(declaration.Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_11()
{
string source1 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (_, _), al _);
}
}
";
var comp1 = CreateCompilation(source1);
StandAlone_11_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
class C
{
static void Main()
{
(al (_, _), al _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_11_VerifySemanticModel(comp2);
}
private static void StandAlone_11_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var declaration = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single();
Assert.Equal("al _", declaration.ToString());
var typeInfo = model.GetTypeInfo(declaration);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declaration);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declaration.Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declaration.Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declaration.Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Equal("al=System.Int32", model.GetAliasInfo(declaration.Type).ToTestDisplayString());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_12()
{
string source1 = @"
using al = System.Int32;
(al (_, _), al _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
StandAlone_11_VerifySemanticModel(comp1);
string source2 = @"
using al = System.Int32;
(al (_, _), al _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_11_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_13()
{
string source1 = @"
class C
{
static void Main()
{
var (a, b);
var (c, d)
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (7,19): error CS1002: ; expected
// var (c, d)
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 19),
// (6,9): error CS0103: The name 'var' does not exist in the current context
// var (a, b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(6, 9),
// (6,14): error CS0103: The name 'a' does not exist in the current context
// var (a, b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "a").WithArguments("a").WithLocation(6, 14),
// (6,17): error CS0103: The name 'b' does not exist in the current context
// var (a, b);
Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(6, 17),
// (7,9): error CS0103: The name 'var' does not exist in the current context
// var (c, d)
Diagnostic(ErrorCode.ERR_NameNotInContext, "var").WithArguments("var").WithLocation(7, 9),
// (7,14): error CS0103: The name 'c' does not exist in the current context
// var (c, d)
Diagnostic(ErrorCode.ERR_NameNotInContext, "c").WithArguments("c").WithLocation(7, 14),
// (7,17): error CS0103: The name 'd' does not exist in the current context
// var (c, d)
Diagnostic(ErrorCode.ERR_NameNotInContext, "d").WithArguments("d").WithLocation(7, 17)
);
var tree = comp1.SyntaxTrees.First();
Assert.False(tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Any());
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_14()
{
string source1 = @"
class C
{
static void Main()
{
((var (a,b), var c), int d);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,11): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)").WithLocation(6, 11),
// (6,22): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c").WithLocation(6, 22),
// (6,30): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(6, 30),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (a,b), var c), int d)").WithLocation(6, 9),
// (6,30): error CS0165: Use of unassigned local variable 'd'
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int d").WithArguments("d").WithLocation(6, 30)
);
StandAlone_14_VerifySemanticModel(comp1, LocalDeclarationKind.DeclarationExpressionVariable);
string source2 = @"
class C
{
static void Main()
{
((var (a,b), var c), int d) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_14_VerifySemanticModel(comp2, LocalDeclarationKind.DeconstructionVariable);
}
private static void StandAlone_14_VerifySemanticModel(CSharpCompilation comp, LocalDeclarationKind localDeclarationKind)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var a", a.ToTestDisplayString());
Assert.Equal(localDeclarationKind, a.GetSymbol<LocalSymbol>().DeclarationKind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var b", b.ToTestDisplayString());
Assert.Equal(localDeclarationKind, b.GetSymbol<LocalSymbol>().DeclarationKind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var c", c.ToTestDisplayString());
Assert.Equal(localDeclarationKind, c.GetSymbol<LocalSymbol>().DeclarationKind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 d", d.ToTestDisplayString());
Assert.Equal(localDeclarationKind, d.GetSymbol<LocalSymbol>().DeclarationKind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ToArray();
Assert.Equal(2, tuples.Length);
Assert.Equal("((var (a,b), var c), int d)", tuples[0].ToString());
typeInfo = model.GetTypeInfo(tuples[0]);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[0]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("(var (a,b), var c)", tuples[1].ToString());
typeInfo = model.GetTypeInfo(tuples[1]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_15()
{
string source1 = @"
((var (a,b), var c), int d);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,8): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(2, 8),
// (2,10): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(2, 10),
// (2,18): error CS7019: Type of 'c' cannot be inferred since its initializer directly or indirectly refers to the definition.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "c").WithArguments("c").WithLocation(2, 18),
// (2,3): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (a,b)").WithLocation(2, 3),
// (2,14): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var c").WithLocation(2, 14),
// (2,22): error CS8185: A declaration is not allowed in this context.
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(2, 22),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (a,b), var c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (a,b), var c), int d)").WithLocation(2, 1)
);
StandAlone_15_VerifySemanticModel(comp1);
string source2 = @"
((var (a,b), var c), int d) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_15_VerifySemanticModel(comp2);
}
private static void StandAlone_15_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var Script.a", a.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, a.Kind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var Script.b", b.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, b.Kind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var Script.c", c.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, c.Kind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 Script.d", d.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, d.Kind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (a,b)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var a, var b)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var c", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("var Script.c", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int d", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
Assert.Equal("System.Int32 Script.d", model.GetSymbolInfo(declarations[2]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ToArray();
Assert.Equal(2, tuples.Length);
Assert.Equal("((var (a,b), var c), int d)", tuples[0].ToString());
typeInfo = model.GetTypeInfo(tuples[0]);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[0]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("(var (a,b), var c)", tuples[1].ToString());
typeInfo = model.GetTypeInfo(tuples[1]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_16()
{
string source1 = @"
class C
{
static void Main()
{
((var (_, _), var _), int _);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,11): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)").WithLocation(6, 11),
// (6,23): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _").WithLocation(6, 23),
// (6,31): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(6, 31),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (_, _), var _), int _)").WithLocation(6, 9)
);
StandAlone_16_VerifySemanticModel(comp1);
string source2 = @"
class C
{
static void Main()
{
((var (_, _), var _), int _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_16_VerifySemanticModel(comp2);
}
private static void StandAlone_16_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
int count = 0;
foreach (var designation in tree.GetCompilationUnitRoot().DescendantNodes().OfType<DiscardDesignationSyntax>())
{
Assert.Null(model.GetDeclaredSymbol(designation));
count++;
}
Assert.Equal(4, count);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(3, declarations.Count());
Assert.Equal("var (_, _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("(var, var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("var _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("var", typeInfo.Type.ToTestDisplayString());
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[1].Type));
Assert.Equal("int _", declarations[2].ToString());
typeInfo = model.GetTypeInfo(declarations[2]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[2].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[2].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[2].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[2].Type));
var tuples = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().ToArray();
Assert.Equal(2, tuples.Length);
Assert.Equal("((var (_, _), var _), int _)", tuples[0].ToString());
typeInfo = model.GetTypeInfo(tuples[0]);
Assert.Equal("(((var, var), var), System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[0]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Equal("(var (_, _), var _)", tuples[1].ToString());
typeInfo = model.GetTypeInfo(tuples[1]);
Assert.Equal("((var, var), var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuples[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuples[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_17()
{
string source1 = @"
((var (_, _), var _), int _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,3): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var (_, _)").WithLocation(2, 3),
// (2,15): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var _").WithLocation(2, 15),
// (2,23): error CS8185: A declaration is not allowed in this context.
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(2, 23),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// ((var (_, _), var _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "((var (_, _), var _), int _)").WithLocation(2, 1)
);
StandAlone_16_VerifySemanticModel(comp1);
string source2 = @"
((var (_, _), var _), int _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_16_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_18()
{
string source1 = @"
class C
{
static void Main()
{
(var ((a,b), c), int d);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((a,b), c)").WithLocation(6, 10),
// (6,26): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(6, 26),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((a,b), c), int d)").WithLocation(6, 9),
// (6,26): error CS0165: Use of unassigned local variable 'd'
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_UseDefViolation, "int d").WithArguments("d").WithLocation(6, 26)
);
StandAlone_18_VerifySemanticModel(comp1, LocalDeclarationKind.DeclarationExpressionVariable);
string source2 = @"
class C
{
static void Main()
{
(var ((a,b), c), int d) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_18_VerifySemanticModel(comp2, LocalDeclarationKind.DeconstructionVariable);
}
private static void StandAlone_18_VerifySemanticModel(CSharpCompilation comp, LocalDeclarationKind localDeclarationKind)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var a", a.ToTestDisplayString());
Assert.Equal(localDeclarationKind, a.GetSymbol<LocalSymbol>().DeclarationKind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var b", b.ToTestDisplayString());
Assert.Equal(localDeclarationKind, b.GetSymbol<LocalSymbol>().DeclarationKind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var c", c.ToTestDisplayString());
Assert.Equal(localDeclarationKind, c.GetSymbol<LocalSymbol>().DeclarationKind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 d", d.ToTestDisplayString());
Assert.Equal(localDeclarationKind, d.GetSymbol<LocalSymbol>().DeclarationKind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var ((a,b), c)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("int d", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 d", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[1].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_19()
{
string source1 = @"
(var ((a,b), c), int d);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,8): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(2, 8),
// (2,10): error CS7019: Type of 'b' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "b").WithArguments("b").WithLocation(2, 10),
// (2,14): error CS7019: Type of 'c' cannot be inferred since its initializer directly or indirectly refers to the definition.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "c").WithArguments("c").WithLocation(2, 14),
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((a,b), c)").WithLocation(2, 2),
// (2,18): error CS8185: A declaration is not allowed in this context.
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int d").WithLocation(2, 18),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((a,b), c), int d);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((a,b), c), int d)").WithLocation(2, 1)
);
StandAlone_19_VerifySemanticModel(comp1);
string source2 = @"
(var ((a,b), c), int d) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_19_VerifySemanticModel(comp2);
}
private static void StandAlone_19_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
var designations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<SingleVariableDesignationSyntax>().ToArray();
Assert.Equal(4, designations.Count());
var a = model.GetDeclaredSymbol(designations[0]);
Assert.Equal("var Script.a", a.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, a.Kind);
var b = model.GetDeclaredSymbol(designations[1]);
Assert.Equal("var Script.b", b.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, b.Kind);
var c = model.GetDeclaredSymbol(designations[2]);
Assert.Equal("var Script.c", c.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, c.Kind);
var d = model.GetDeclaredSymbol(designations[3]);
Assert.Equal("System.Int32 Script.d", d.ToTestDisplayString());
Assert.Equal(SymbolKind.Field, d.Kind);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var ((a,b), c)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("((var a, var b), var c)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("int d", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
Assert.Equal("System.Int32 Script.d", model.GetSymbolInfo(declarations[1]).Symbol.ToTestDisplayString());
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[1].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("(((var a, var b), var c), System.Int32 d)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_20()
{
string source1 = @"
class C
{
static void Main()
{
(var ((_, _), _), int _);
}
}
";
var comp1 = CreateCompilation(source1);
comp1.VerifyDiagnostics(
// (6,10): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((_, _), _)").WithLocation(6, 10),
// (6,27): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(6, 27),
// (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((_, _), _), int _)").WithLocation(6, 9)
);
StandAlone_20_VerifySemanticModel(comp1);
string source2 = @"
class C
{
static void Main()
{
(var ((_, _), _), int _) = D;
}
}
";
var comp2 = CreateCompilation(source2);
StandAlone_20_VerifySemanticModel(comp2);
}
private static void StandAlone_20_VerifySemanticModel(CSharpCompilation comp)
{
var tree = comp.SyntaxTrees.First();
var model = comp.GetSemanticModel(tree);
int count = 0;
foreach (var designation in tree.GetCompilationUnitRoot().DescendantNodes().OfType<DiscardDesignationSyntax>())
{
Assert.Null(model.GetDeclaredSymbol(designation));
count++;
}
Assert.Equal(4, count);
var declarations = tree.GetCompilationUnitRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().ToArray();
Assert.Equal(2, declarations.Count());
Assert.Equal("var ((_, _), _)", declarations[0].ToString());
var typeInfo = model.GetTypeInfo(declarations[0]);
Assert.Equal("((var, var), var)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0]).IsIdentity);
var symbolInfo = model.GetSymbolInfo(declarations[0]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[0].Type);
Assert.Null(typeInfo.Type);
Assert.Null(typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[0].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[0].Type);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
Assert.Null(model.GetAliasInfo(declarations[0].Type));
Assert.Equal("int _", declarations[1].ToString());
typeInfo = model.GetTypeInfo(declarations[1]);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1]).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1]);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
typeInfo = model.GetTypeInfo(declarations[1].Type);
Assert.Equal("System.Int32", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(declarations[1].Type).IsIdentity);
symbolInfo = model.GetSymbolInfo(declarations[1].Type);
Assert.Equal("System.Int32", symbolInfo.Symbol.ToTestDisplayString());
Assert.Null(model.GetAliasInfo(declarations[1].Type));
var tuple = tree.GetCompilationUnitRoot().DescendantNodes().OfType<TupleExpressionSyntax>().Single();
typeInfo = model.GetTypeInfo(tuple);
Assert.Equal("(((var, var), var), System.Int32)", typeInfo.Type.ToTestDisplayString());
Assert.Equal(typeInfo.Type, typeInfo.ConvertedType);
Assert.True(model.GetConversion(tuple).IsIdentity);
symbolInfo = model.GetSymbolInfo(tuple);
Assert.Null(symbolInfo.Symbol);
Assert.Empty(symbolInfo.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason);
}
[Fact, WorkItem(17572, "https://github.com/dotnet/roslyn/issues/17572")]
public void StandAlone_21()
{
string source1 = @"
(var ((_, _), _), int _);
";
var comp1 = CreateCompilation(source1, parseOptions: TestOptions.Script);
comp1.VerifyDiagnostics(
// (2,2): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "var ((_, _), _)").WithLocation(2, 2),
// (2,19): error CS8185: A declaration is not allowed in this context.
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_DeclarationExpressionNotPermitted, "int _").WithLocation(2, 19),
// (2,1): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement
// (var ((_, _), _), int _);
Diagnostic(ErrorCode.ERR_IllegalStatement, "(var ((_, _), _), int _)").WithLocation(2, 1)
);
StandAlone_20_VerifySemanticModel(comp1);
string source2 = @"
(var ((_, _), _), int _) = D;
";
var comp2 = CreateCompilation(source2, parseOptions: TestOptions.Script);
StandAlone_20_VerifySemanticModel(comp2);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DiscardVoid_01()
{
var source = @"class C
{
static void Main()
{
(_, _) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,22): error CS8210: A tuple may not contain a value of type 'void'.
// (_, _) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 22)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_01()
{
var source = @"class C
{
static void Main()
{
(int x, void y) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS1547: Keyword 'void' cannot be used in this context
// (int x, void y) = (1, Main());
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(5, 17),
// (5,31): error CS8210: A tuple may not contain a value of type 'void'.
// (int x, void y) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 31)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_02()
{
var source = @"class C
{
static void Main()
{
var (x, y) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,26): error CS8210: A tuple may not contain a value of type 'void'.
// var (x, y) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 26)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_03()
{
var source = @"class C
{
static void Main()
{
(int x, void y) = (1, 2);
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,17): error CS1547: Keyword 'void' cannot be used in this context
// (int x, void y) = (1, 2);
Diagnostic(ErrorCode.ERR_NoVoidHere, "void").WithLocation(5, 17),
// (5,31): error CS0029: Cannot implicitly convert type 'int' to 'void'
// (int x, void y) = (1, 2);
Diagnostic(ErrorCode.ERR_NoImplicitConv, "2").WithArguments("int", "void").WithLocation(5, 31)
);
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var two = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "2").Single();
var type = model.GetTypeInfo(two);
Assert.Equal(SpecialType.System_Int32, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Int32, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(two).Kind);
var symbols = model.GetSymbolInfo(two);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)two.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[Fact, WorkItem(17921, "https://github.com/dotnet/roslyn/issues/17921")]
public void DeconstructVoid_04()
{
var source = @"class C
{
static void Main()
{
(int x, int y) = (1, Main());
}
}";
var comp = CreateCompilation(source);
comp.VerifyDiagnostics(
// (5,30): error CS8210: A tuple may not contain a value of type 'void'.
// (int x, int y) = (1, Main());
Diagnostic(ErrorCode.ERR_VoidInTuple, "Main()").WithLocation(5, 30)
);
var main = comp.GetMember<MethodSymbol>("C.Main");
var tree = comp.SyntaxTrees[0];
var model = comp.GetSemanticModel(tree);
var mainCall = tree.GetRoot().DescendantNodes().OfType<ExpressionSyntax>().Where(n => n.ToString() == "Main()").Single();
var type = model.GetTypeInfo(mainCall);
Assert.Equal(SpecialType.System_Void, type.Type.SpecialType);
Assert.Equal(SpecialType.System_Void, type.ConvertedType.SpecialType);
Assert.Equal(ConversionKind.Identity, model.GetConversion(mainCall).Kind);
var symbols = model.GetSymbolInfo(mainCall);
Assert.Equal(symbols.Symbol, main.GetPublicSymbol());
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
// the ArgumentSyntax above a tuple element doesn't support GetTypeInfo or GetSymbolInfo.
var argument = (ArgumentSyntax)mainCall.Parent;
type = model.GetTypeInfo(argument);
Assert.Null(type.Type);
Assert.Null(type.ConvertedType);
symbols = model.GetSymbolInfo(argument);
Assert.Null(symbols.Symbol);
Assert.Empty(symbols.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbols.CandidateReason);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DiscardDeclarationExpression_IOperation()
{
string source = @"
class C
{
void M()
{
/*<bind>*/var (_, _) = (0, 0)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32, System.Int32)) (Syntax: 'var (_, _) = (0, 0)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32, System.Int32)) (Syntax: 'var (_, _)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(_, _)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(0, 0)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DiscardDeclarationAssignment_IOperation()
{
string source = @"
class C
{
void M()
{
int x;
/*<bind>*/(x, _) = (0, 0)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, _) = (0, 0)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 x, System.Int32)) (Syntax: '(x, _)')
NaturalType: (System.Int32 x, System.Int32)
Elements(2):
ILocalReferenceOperation: x (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'x')
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: '_')
Right:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(0, 0)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<AssignmentExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void DiscardOutVarDeclaration_IOperation()
{
string source = @"
class C
{
void M()
{
M2(out /*<bind>*/var _/*</bind>*/);
}
void M2(out int x)
{
x = 0;
}
}
";
string expectedOperationTree = @"
IDiscardOperation (Symbol: System.Int32 _) (OperationKind.Discard, Type: System.Int32) (Syntax: 'var _')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<DeclarationExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_1()
{
var text = @"
class C
{
static void Main()
{
foreach ((var i, i))
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(var i, i)").WithLocation(6, 18),
// (6,23): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'i'.
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "i").WithArguments("i").WithLocation(6, 23),
// (6,26): error CS0841: Cannot use local variable 'i' before it is declared
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "i").WithArguments("i").WithLocation(6, 26),
// (6,28): error CS1515: 'in' expected
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_InExpected, ")").WithLocation(6, 28),
// (6,28): error CS1525: Invalid expression term ')'
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 28),
// (6,29): error CS1525: Invalid expression term '}'
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}").WithLocation(6, 29),
// (6,29): error CS1002: ; expected
// foreach ((var i, i))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 29)
);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_2()
{
var text = @"
class C
{
static void Main()
{
(var i, i) = ;
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'i'.
// (var i, i) = ;
Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "i").WithArguments("i").WithLocation(6, 14),
// (6,17): error CS0841: Cannot use local variable 'i' before it is declared
// (var i, i) = ;
Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "i").WithArguments("i").WithLocation(6, 17),
// (6,22): error CS1525: Invalid expression term ';'
// (var i, i) = ;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 22)
);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_3()
{
var text = @"
class C
{
static void Main()
{
foreach ((int i, i))
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,18): error CS8186: A foreach loop must declare its iteration variables.
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_MustDeclareForeachIteration, "(int i, i)").WithLocation(6, 18),
// (6,26): error CS1656: Cannot assign to 'i' because it is a 'foreach iteration variable'
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "i").WithArguments("i", "foreach iteration variable").WithLocation(6, 26),
// (6,28): error CS1515: 'in' expected
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_InExpected, ")").WithLocation(6, 28),
// (6,28): error CS1525: Invalid expression term ')'
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 28),
// (6,29): error CS1525: Invalid expression term '}'
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "").WithArguments("}").WithLocation(6, 29),
// (6,29): error CS1002: ; expected
// foreach ((int i, i))
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 29)
);
}
[Fact]
[WorkItem(46165, "https://github.com/dotnet/roslyn/issues/46165")]
public void Issue46165_4()
{
var text = @"
class C
{
static void Main()
{
(int i, i) = ;
}
}";
CreateCompilation(text).VerifyEmitDiagnostics(
// (6,22): error CS1525: Invalid expression term ';'
// (int i, i) = ;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(6, 22)
);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/VisualBasic/Highlighting/KeywordHighlighters/TryBlockHighlighter.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.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class TryBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then
Return
End If
Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing Then
Return
End If
With tryBlock
highlights.Add(.TryStatement.TryKeyword.Span)
HighlightRelatedStatements(tryBlock, highlights)
For Each catchBlock In .CatchBlocks
With catchBlock.CatchStatement
highlights.Add(.CatchKeyword.Span)
If .WhenClause IsNot Nothing Then
highlights.Add(.WhenClause.WhenKeyword.Span)
End If
End With
HighlightRelatedStatements(catchBlock, highlights)
Next
If .FinallyBlock IsNot Nothing Then
highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span)
End If
highlights.Add(.EndTryStatement.Span)
End With
End Sub
Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan))
If node.Kind = SyntaxKind.ExitTryStatement Then
highlights.Add(node.Span)
Else
For Each childNodeOrToken In node.ChildNodesAndTokens()
If childNodeOrToken.IsToken Then
Continue For
End If
Dim child = childNodeOrToken.AsNode()
If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(child, highlights)
End If
Next
End If
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.Implementation.Highlighting
Imports Microsoft.CodeAnalysis.Host.Mef
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.KeywordHighlighting
<ExportHighlighter(LanguageNames.VisualBasic)>
Friend Class TryBlockHighlighter
Inherits AbstractKeywordHighlighter(Of SyntaxNode)
<ImportingConstructor>
<Obsolete(MefConstruction.ImportingConstructorMessage, True)>
Public Sub New()
End Sub
Protected Overloads Overrides Sub AddHighlights(node As SyntaxNode, highlights As List(Of TextSpan), cancellationToken As CancellationToken)
If TypeOf node Is ExitStatementSyntax AndAlso node.Kind <> SyntaxKind.ExitTryStatement Then
Return
End If
Dim tryBlock = node.GetAncestor(Of TryBlockSyntax)()
If tryBlock Is Nothing Then
Return
End If
With tryBlock
highlights.Add(.TryStatement.TryKeyword.Span)
HighlightRelatedStatements(tryBlock, highlights)
For Each catchBlock In .CatchBlocks
With catchBlock.CatchStatement
highlights.Add(.CatchKeyword.Span)
If .WhenClause IsNot Nothing Then
highlights.Add(.WhenClause.WhenKeyword.Span)
End If
End With
HighlightRelatedStatements(catchBlock, highlights)
Next
If .FinallyBlock IsNot Nothing Then
highlights.Add(.FinallyBlock.FinallyStatement.FinallyKeyword.Span)
End If
highlights.Add(.EndTryStatement.Span)
End With
End Sub
Private Sub HighlightRelatedStatements(node As SyntaxNode, highlights As List(Of TextSpan))
If node.Kind = SyntaxKind.ExitTryStatement Then
highlights.Add(node.Span)
Else
For Each childNodeOrToken In node.ChildNodesAndTokens()
If childNodeOrToken.IsToken Then
Continue For
End If
Dim child = childNodeOrToken.AsNode()
If Not TypeOf child Is TryBlockSyntax AndAlso Not TypeOf child Is LambdaExpressionSyntax Then
HighlightRelatedStatements(child, highlights)
End If
Next
End If
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/VisualBasicTest/ConvertForEachToFor/ConvertForEachToForTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForEachToFor
Partial Public Class ConvertForEachToForTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(
workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertForEachToForCodeRefactoringProvider()
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Body() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Console.WriteLine(a) : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function BlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For Each [||] a In array ' comment
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For {|Rename:i|} = 0 To array.Length - 1 ' comment
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment2() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment3() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next a ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next i ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment4() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3} ' test
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1 ' test
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment7() As Task
Dim initial = "
Class Test
Sub Method()
' test
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
' test
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestCommentsLiveBetweenForEachAndArrayDeclaration() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim Expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, Expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CommentNotSupportedCommentsAfterLineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _ ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function LineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _
In
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionStatement() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionConflict() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = 1
For Each [||] a In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = 1
Dim {|Rename:array1|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array1.Length - 1
Dim a = array1(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim a = array(i1)
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function VariableWritten() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
a = 1
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
{|Warning:Dim a = array(i)|}
a = 1
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
Public Async Function StructPropertyReadFromAndAssignedToLocal() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
Dim b = a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Dim b = a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function StructPropertyRead() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongCaretPosition() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {1, 2, 3}
[||]
Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestBefore() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[||] For Each a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestAfter() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each a In array [||]
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestSelection() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[|For Each a In array
Next|]
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Field() As Task
Dim initial = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For Each [||] a In list
Next
End Sub
End Class
"
Dim expected = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For {|Rename:i|} = 0 To list.Length - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function [Interface]() As Task
Dim initial = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For [||] Each a In list
Next
End Sub
End Class
"
Dim expected = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function ExplicitInterface() As Task
Dim initial = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
For [||] Each a In list
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Dim expected = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
Dim {|Rename:list1|} = DirectCast(list, IReadOnlyList(Of Integer))
For {|Rename:i|} = 0 To list1.Count - 1
Dim a = list1(i)
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each a [||] In New Integer() {}
For Each b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext2() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {}
For Each [||] b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {}
Console.WriteLine(a)
Next b
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function KeepNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next a
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next i
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict2() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] i In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim i = array(i1)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UseTypeAsUsedInForeach() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a As Integer In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a As Integer = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UniqueLocalName() As Task
Dim initial = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
For Each [||] a In New List(Of Integer)()
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
Dim {|Rename:list|} = New List(Of Integer)()
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, 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.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Imports Microsoft.CodeAnalysis.VisualBasic.ConvertForEachToFor
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.ConvertForEachToFor
Partial Public Class ConvertForEachToForTests
Inherits AbstractVisualBasicCodeActionTest
Protected Overrides Function CreateCodeRefactoringProvider(
workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New VisualBasicConvertForEachToForCodeRefactoringProvider()
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function EmptyBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Body() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array : Console.WriteLine(a) : Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function BlockBody() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For Each [||] a In array ' comment
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
' comment
For {|Rename:i|} = 0 To array.Length - 1 ' comment
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment2() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
' comment
Console.WriteLine(a)
Next ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment3() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each [||] a In array
Console.WriteLine(a)
Next a ' comment
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Console.WriteLine(a)
Next i ' comment
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment4() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3} ' test
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1 ' test
Dim a = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Comment7() As Task
Dim initial = "
Class Test
Sub Method()
' test
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
' test
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestCommentsLiveBetweenForEachAndArrayDeclaration() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim Expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, Expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CommentNotSupportedCommentsAfterLineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _ ' test
In ' test
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function LineContinuation() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a _
In
New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionStatement() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function CollectionConflict() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = 1
For Each [||] a In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = 1
Dim {|Rename:array1|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array1.Length - 1
Dim a = array1(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim a = array(i1)
Dim i = 1
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function VariableWritten() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
a = 1
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
{|Warning:Dim a = array(i)|}
a = 1
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
Public Async Function StructPropertyReadFromAndAssignedToLocal() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
Dim b = a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Dim b = a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function StructPropertyRead() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer?() {1, 2, 3}
a.Value
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer?() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
a.Value
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongCaretPosition() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {1, 2, 3}
[||]
Next
End Sub
End Class
"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestBefore() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[||] For Each a In array
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestAfter() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For Each a In array [||]
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<WorkItem(35525, "https://github.com/dotnet/roslyn/issues/35525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function TestSelection() As Task
Dim initial = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
[|For Each a In array
Next|]
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim array = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function Field() As Task
Dim initial = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For Each [||] a In list
Next
End Sub
End Class
"
Dim expected = "
Class Test
Dim list As Integer() = New Integer() {1, 2, 3}
Sub Method()
For {|Rename:i|} = 0 To list.Length - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function [Interface]() As Task
Dim initial = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For [||] Each a In list
Next
End Sub
End Class
"
Dim expected = "
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = DirectCast(New Integer() {1, 2, 3}, IList(Of Integer))
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function ExplicitInterface() As Task
Dim initial = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
For [||] Each a In list
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Dim expected = "
Imports System
Imports System.Collections
Imports System.Collections.Generic
Class Test
Sub Method()
Dim list = New Explicit()
Dim {|Rename:list1|} = DirectCast(list, IReadOnlyList(Of Integer))
For {|Rename:i|} = 0 To list1.Count - 1
Dim a = list1(i)
Console.WriteLine(a)
Next
End Sub
End Class
Class Explicit
Implements IReadOnlyList(Of Integer)
Default Public ReadOnly Property ItemExplicit(index As Integer) As Integer Implements IReadOnlyList(Of Integer).Item
Get
Throw New NotImplementedException()
End Get
End Property
Public ReadOnly Property CountExplicit As Integer Implements IReadOnlyCollection(Of Integer).Count
Get
Throw New NotImplementedException()
End Get
End Property
Public Function GetEnumeratorExplicit() As IEnumerator(Of Integer) Implements IEnumerable(Of Integer).GetEnumerator
Throw New NotImplementedException()
End Function
Private Function IEnumerable_GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
Throw New NotImplementedException()
End Function
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each a [||] In New Integer() {}
For Each b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function MultipleNext2() As Task
Dim initial = "
Class Test
Sub Method()
For Each a In New Integer() {}
For Each [||] b In New Integer() {}
Console.WriteLine(a)
Next b, a
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function WrongNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {}
Console.WriteLine(a)
Next b
End Sub
End Class"
Await TestMissingInRegularAndScriptAsync(initial)
End Function
<WorkItem(31621, "https://github.com/dotnet/roslyn/issues/31621")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function KeepNext() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a In New Integer() {1, 2, 3}
Next a
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a = array(i)
Next i
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function IndexConflict2() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] i In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i1|} = 0 To array.Length - 1
Dim i = array(i1)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UseTypeAsUsedInForeach() As Task
Dim initial = "
Class Test
Sub Method()
For Each [||] a As Integer In New Integer() {1, 2, 3}
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Class Test
Sub Method()
Dim {|Rename:array|} = New Integer() {1, 2, 3}
For {|Rename:i|} = 0 To array.Length - 1
Dim a As Integer = array(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConvertForEachToFor)>
Public Async Function UniqueLocalName() As Task
Dim initial = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
For Each [||] a In New List(Of Integer)()
Console.WriteLine(a)
Next
End Sub
End Class
"
Dim expected = "
Imports System
Imports System.Collections.Generic
Class Test
Sub Method()
Dim {|Rename:list|} = New List(Of Integer)()
For {|Rename:i|} = 0 To list.Count - 1
Dim a = list(i)
Console.WriteLine(a)
Next
End Sub
End Class
"
Await TestInRegularAndScriptAsync(initial, expected)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_IfStatement.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.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Partial Friend Class EndConstructStatementVisitor
Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As AbstractEndConstructResult
Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineIfBlockSyntax)().Any(Function(block) block.EndIfStatement.IsMissing)
If needsEnd Then
Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart)
Return New SpitLinesResult({"", aligningWhitespace & "End If"})
Else
Return Nothing
End If
End Function
Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As AbstractEndConstructResult
Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart)
Dim indentedWhitespace = aligningWhitespace & " "
Dim whitespaceTrivia = {SyntaxFactory.WhitespaceTrivia(aligningWhitespace)}.ToSyntaxTriviaList()
Dim endOfLine = SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)
Dim elseBlock As ElseBlockSyntax = Nothing
If node.ElseClause IsNot Nothing Then
Dim trailingTrivia = If(node.ElseClause.ElseKeyword.HasTrailingTrivia AndAlso node.ElseClause.ElseKeyword.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia),
node.ElseClause.ElseKeyword.TrailingTrivia,
{endOfLine}.ToSyntaxTriviaList())
elseBlock = SyntaxFactory.ElseBlock(SyntaxFactory.ElseStatement(SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.ElseKeyword, trailingTrivia)),
ConvertSingleLineStatementsToMultiLineStatements(node.ElseClause.Statements, indentedWhitespace))
End If
Dim ifBlock = SyntaxFactory.MultiLineIfBlock(
SyntaxFactory.IfStatement(node.IfKeyword, node.Condition, node.ThenKeyword).WithTrailingTrivia(endOfLine),
ConvertSingleLineStatementsToMultiLineStatements(node.Statements, indentedWhitespace),
New SyntaxList(Of ElseIfBlockSyntax),
elseBlock,
SyntaxFactory.EndIfStatement(
SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.EndKeyword, {SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList(), "End"),
SyntaxFactory.Token(Nothing, SyntaxKind.IfKeyword, {endOfLine}.ToSyntaxTriviaList(), "If")))
Dim position = If(ifBlock.Statements.Any(), ifBlock.Statements(0).SpanStart, ifBlock.IfStatement.Span.End + _state.NewLineCharacter.Length)
Dim ifNodeToken As SyntaxNodeOrToken = ifBlock
Return New ReplaceSpanResult(node.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), ifNodeToken.ToFullString(), position)
End Function
''' <summary>
''' Given a separatedSyntaxList of statements separated by colons, converts them to a
''' separate syntax list of statements separated by newlines
''' </summary>
''' <param name="statements">The list of statements to convert.</param>
''' <param name="indentedWhitespace">The whitespace to indent with.</param>
Private Function ConvertSingleLineStatementsToMultiLineStatements(statements As SyntaxList(Of StatementSyntax), indentedWhitespace As String) As SyntaxList(Of StatementSyntax)
If statements = Nothing OrElse statements.Count = 0 Then
' Return an empty statement with a newline
Return SyntaxFactory.List({DirectCast(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken, SyntaxFactory.TriviaList(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)))), StatementSyntax)})
End If
Dim indentedWhitespaceTrivia = SpecializedCollections.SingletonEnumerable(SyntaxFactory.WhitespaceTrivia(indentedWhitespace))
Dim newList As New List(Of StatementSyntax)(capacity:=statements.Count)
Dim triviaLeftForNextStatement As IEnumerable(Of SyntaxTrivia) = New List(Of SyntaxTrivia)
' If the last statement itself is an End If statement, we should skip it
Dim lastStatementToProcess = statements.Count - 1
If statements.LastOrDefault().IsKind(SyntaxKind.EndIfStatement) Then
lastStatementToProcess = statements.Count - 2
End If
For i = 0 To lastStatementToProcess
Dim statement = statements(i)
' Add the new whitespace on the start of the statement
If statement.Kind <> SyntaxKind.EmptyStatement OrElse statement.HasTrailingTrivia Then
Dim leadingTrivia = indentedWhitespaceTrivia.Concat(triviaLeftForNextStatement.Concat(statement.GetLeadingTrivia()).WithoutLeadingWhitespaceOrEndOfLine())
statement = statement.WithLeadingTrivia(leadingTrivia)
End If
' We want to drop any whitespace trivia from the
' end
Dim trailingTrivia = New List(Of SyntaxTrivia)
Dim separator As SyntaxTrivia = Nothing
Dim lastToken = statement.GetLastToken(includeZeroWidth:=True)
For Each trivia In lastToken.TrailingTrivia
If trivia.Kind = SyntaxKind.ColonTrivia Then
separator = trivia
Exit For
End If
trailingTrivia.Add(trivia)
Next
Do While trailingTrivia.Count > 0 AndAlso trailingTrivia.Last().Kind = SyntaxKind.WhitespaceTrivia
trailingTrivia.RemoveAt(trailingTrivia.Count - 1)
Loop
If separator.Kind <> SyntaxKind.None OrElse Not trailingTrivia.Any Then
trailingTrivia.Add(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
End If
statement = statement.WithTrailingTrivia(trailingTrivia)
newList.Add(statement)
triviaLeftForNextStatement = lastToken.TrailingTrivia.SkipWhile(Function(t) t <> separator).Where(Function(t) t.Kind <> SyntaxKind.ColonTrivia)
Next
Return SyntaxFactory.List(newList)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text.Shared.Extensions
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration
Partial Friend Class EndConstructStatementVisitor
Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As AbstractEndConstructResult
Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineIfBlockSyntax)().Any(Function(block) block.EndIfStatement.IsMissing)
If needsEnd Then
Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart)
Return New SpitLinesResult({"", aligningWhitespace & "End If"})
Else
Return Nothing
End If
End Function
Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As AbstractEndConstructResult
Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart)
Dim indentedWhitespace = aligningWhitespace & " "
Dim whitespaceTrivia = {SyntaxFactory.WhitespaceTrivia(aligningWhitespace)}.ToSyntaxTriviaList()
Dim endOfLine = SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)
Dim elseBlock As ElseBlockSyntax = Nothing
If node.ElseClause IsNot Nothing Then
Dim trailingTrivia = If(node.ElseClause.ElseKeyword.HasTrailingTrivia AndAlso node.ElseClause.ElseKeyword.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia),
node.ElseClause.ElseKeyword.TrailingTrivia,
{endOfLine}.ToSyntaxTriviaList())
elseBlock = SyntaxFactory.ElseBlock(SyntaxFactory.ElseStatement(SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.ElseKeyword, trailingTrivia)),
ConvertSingleLineStatementsToMultiLineStatements(node.ElseClause.Statements, indentedWhitespace))
End If
Dim ifBlock = SyntaxFactory.MultiLineIfBlock(
SyntaxFactory.IfStatement(node.IfKeyword, node.Condition, node.ThenKeyword).WithTrailingTrivia(endOfLine),
ConvertSingleLineStatementsToMultiLineStatements(node.Statements, indentedWhitespace),
New SyntaxList(Of ElseIfBlockSyntax),
elseBlock,
SyntaxFactory.EndIfStatement(
SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.EndKeyword, {SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList(), "End"),
SyntaxFactory.Token(Nothing, SyntaxKind.IfKeyword, {endOfLine}.ToSyntaxTriviaList(), "If")))
Dim position = If(ifBlock.Statements.Any(), ifBlock.Statements(0).SpanStart, ifBlock.IfStatement.Span.End + _state.NewLineCharacter.Length)
Dim ifNodeToken As SyntaxNodeOrToken = ifBlock
Return New ReplaceSpanResult(node.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), ifNodeToken.ToFullString(), position)
End Function
''' <summary>
''' Given a separatedSyntaxList of statements separated by colons, converts them to a
''' separate syntax list of statements separated by newlines
''' </summary>
''' <param name="statements">The list of statements to convert.</param>
''' <param name="indentedWhitespace">The whitespace to indent with.</param>
Private Function ConvertSingleLineStatementsToMultiLineStatements(statements As SyntaxList(Of StatementSyntax), indentedWhitespace As String) As SyntaxList(Of StatementSyntax)
If statements = Nothing OrElse statements.Count = 0 Then
' Return an empty statement with a newline
Return SyntaxFactory.List({DirectCast(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken, SyntaxFactory.TriviaList(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)))), StatementSyntax)})
End If
Dim indentedWhitespaceTrivia = SpecializedCollections.SingletonEnumerable(SyntaxFactory.WhitespaceTrivia(indentedWhitespace))
Dim newList As New List(Of StatementSyntax)(capacity:=statements.Count)
Dim triviaLeftForNextStatement As IEnumerable(Of SyntaxTrivia) = New List(Of SyntaxTrivia)
' If the last statement itself is an End If statement, we should skip it
Dim lastStatementToProcess = statements.Count - 1
If statements.LastOrDefault().IsKind(SyntaxKind.EndIfStatement) Then
lastStatementToProcess = statements.Count - 2
End If
For i = 0 To lastStatementToProcess
Dim statement = statements(i)
' Add the new whitespace on the start of the statement
If statement.Kind <> SyntaxKind.EmptyStatement OrElse statement.HasTrailingTrivia Then
Dim leadingTrivia = indentedWhitespaceTrivia.Concat(triviaLeftForNextStatement.Concat(statement.GetLeadingTrivia()).WithoutLeadingWhitespaceOrEndOfLine())
statement = statement.WithLeadingTrivia(leadingTrivia)
End If
' We want to drop any whitespace trivia from the
' end
Dim trailingTrivia = New List(Of SyntaxTrivia)
Dim separator As SyntaxTrivia = Nothing
Dim lastToken = statement.GetLastToken(includeZeroWidth:=True)
For Each trivia In lastToken.TrailingTrivia
If trivia.Kind = SyntaxKind.ColonTrivia Then
separator = trivia
Exit For
End If
trailingTrivia.Add(trivia)
Next
Do While trailingTrivia.Count > 0 AndAlso trailingTrivia.Last().Kind = SyntaxKind.WhitespaceTrivia
trailingTrivia.RemoveAt(trailingTrivia.Count - 1)
Loop
If separator.Kind <> SyntaxKind.None OrElse Not trailingTrivia.Any Then
trailingTrivia.Add(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter))
End If
statement = statement.WithTrailingTrivia(trailingTrivia)
newList.Add(statement)
triviaLeftForNextStatement = lastToken.TrailingTrivia.SkipWhile(Function(t) t <> separator).Where(Function(t) t.Kind <> SyntaxKind.ColonTrivia)
Next
Return SyntaxFactory.List(newList)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Portable/Utilities/IValueSetFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A value set factory, which can be used to create a value set instance. A given instance of <see cref="IValueSetFactory"/>
/// supports only one type for the value sets it can produce.
/// </summary>
internal interface IValueSetFactory
{
/// <summary>
/// Returns a value set that includes any values that satisfy the given relation when compared to the given value.
/// </summary>
IValueSet Related(BinaryOperatorKind relation, ConstantValue value);
/// <summary>
/// Returns true iff the values are related according to the given relation.
/// </summary>
bool Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right);
/// <summary>
/// Produce a random value set with the given expected size for testing.
/// </summary>
IValueSet Random(int expectedSize, Random random);
/// <summary>
/// Produce a random value for testing.
/// </summary>
ConstantValue RandomValue(Random random);
/// <summary>
/// The set containing all values of the type.
/// </summary>
IValueSet AllValues { get; }
/// <summary>
/// The empty set of values.
/// </summary>
IValueSet NoValues { get; }
}
/// <summary>
/// A value set factory, which can be used to create a value set instance. Like <see cref="ValueSetFactory"/> but strongly
/// typed to <typeparamref name="T"/>.
/// </summary>
internal interface IValueSetFactory<T> : IValueSetFactory
{
/// <summary>
/// Returns a value set that includes any values that satisfy the given relation when compared to the given value.
/// </summary>
IValueSet<T> Related(BinaryOperatorKind relation, T value);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A value set factory, which can be used to create a value set instance. A given instance of <see cref="IValueSetFactory"/>
/// supports only one type for the value sets it can produce.
/// </summary>
internal interface IValueSetFactory
{
/// <summary>
/// Returns a value set that includes any values that satisfy the given relation when compared to the given value.
/// </summary>
IValueSet Related(BinaryOperatorKind relation, ConstantValue value);
/// <summary>
/// Returns true iff the values are related according to the given relation.
/// </summary>
bool Related(BinaryOperatorKind relation, ConstantValue left, ConstantValue right);
/// <summary>
/// Produce a random value set with the given expected size for testing.
/// </summary>
IValueSet Random(int expectedSize, Random random);
/// <summary>
/// Produce a random value for testing.
/// </summary>
ConstantValue RandomValue(Random random);
/// <summary>
/// The set containing all values of the type.
/// </summary>
IValueSet AllValues { get; }
/// <summary>
/// The empty set of values.
/// </summary>
IValueSet NoValues { get; }
}
/// <summary>
/// A value set factory, which can be used to create a value set instance. Like <see cref="ValueSetFactory"/> but strongly
/// typed to <typeparamref name="T"/>.
/// </summary>
internal interface IValueSetFactory<T> : IValueSetFactory
{
/// <summary>
/// Returns a value set that includes any values that satisfy the given relation when compared to the given value.
/// </summary>
IValueSet<T> Related(BinaryOperatorKind relation, T value);
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DefaultKeywordRecommender.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public DefaultKeywordRecommender()
: base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
IsValidPreProcessorContext(context) ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsAnyExpressionContext ||
context.TargetToken.IsSwitchLabelContext() ||
context.SyntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken);
}
private static bool IsValidPreProcessorContext(CSharpSyntaxContext context)
{
// cases:
// #line |
// #line d|
// # line |
// # line d|
var previousToken1 = context.TargetToken;
var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
return
previousToken1.Kind() == SyntaxKind.LineKeyword &&
previousToken2.Kind() == SyntaxKind.HashToken;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery;
namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders
{
internal class DefaultKeywordRecommender : AbstractSyntacticSingleKeywordRecommender
{
public DefaultKeywordRecommender()
: base(SyntaxKind.DefaultKeyword, isValidInPreprocessorContext: true)
{
}
protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken)
{
return
IsValidPreProcessorContext(context) ||
context.IsStatementContext ||
context.IsGlobalStatementContext ||
context.IsAnyExpressionContext ||
context.TargetToken.IsSwitchLabelContext() ||
context.SyntaxTree.IsTypeParameterConstraintStartContext(position, context.LeftToken);
}
private static bool IsValidPreProcessorContext(CSharpSyntaxContext context)
{
// cases:
// #line |
// #line d|
// # line |
// # line d|
var previousToken1 = context.TargetToken;
var previousToken2 = previousToken1.GetPreviousToken(includeSkipped: true);
return
previousToken1.Kind() == SyntaxKind.LineKeyword &&
previousToken2.Kind() == SyntaxKind.HashToken;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/Core/Utilities/NameGenerator.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class NameGenerator
{
/// <summary>
/// Transforms baseName into a name that does not conflict with any name in 'reservedNames'
/// </summary>
public static string EnsureUniqueness(
string baseName,
IEnumerable<string> reservedNames,
bool isCaseSensitive = true)
{
using var namesDisposer = ArrayBuilder<string>.GetInstance(out var names);
using var isFixedDisposer = ArrayBuilder<bool>.GetInstance(out var isFixed);
using var nameSetDisposer = PooledHashSet<string>.GetInstance(out var nameSet);
names.Add(baseName);
isFixed.Add(false);
foreach (var reservedName in reservedNames)
{
if (nameSet.Add(reservedName))
{
names.Add(reservedName);
isFixed.Add(true);
}
}
EnsureUniquenessInPlace(names, isFixed, isCaseSensitive: isCaseSensitive);
return names.First();
}
public static ImmutableArray<string> EnsureUniqueness(
ImmutableArray<string> names,
Func<string, bool>? canUse = null,
bool isCaseSensitive = true)
{
using var isFixedDisposer = ArrayBuilder<bool>.GetInstance(names.Length, fillWithValue: false, out var isFixed);
var result = ArrayBuilder<string>.GetInstance(names.Length);
result.AddRange(names);
EnsureUniquenessInPlace(result, isFixed, canUse, isCaseSensitive);
return result.ToImmutableAndFree();
}
/// <summary>
/// Ensures that any 'names' is unique and does not collide with any other name. Names that
/// are marked as IsFixed can not be touched. This does mean that if there are two names
/// that are the same, and both are fixed that you will end up with non-unique names at the
/// end.
/// </summary>
public static ImmutableArray<string> EnsureUniqueness(
ImmutableArray<string> names,
ImmutableArray<bool> isFixed,
Func<string, bool>? canUse = null,
bool isCaseSensitive = true)
{
using var isFixedDisposer = ArrayBuilder<bool>.GetInstance(names.Length, out var isFixedBuilder);
isFixedBuilder.AddRange(isFixed);
var result = ArrayBuilder<string>.GetInstance(names.Length);
result.AddRange(names);
EnsureUniquenessInPlace(result, isFixedBuilder, canUse, isCaseSensitive);
return result.ToImmutableAndFree();
}
/// <summary>
/// Updates the names in <paramref name="names"/> to be unique. A name at a particular
/// index <c>i</c> will not be touched if <c>isFixed[i]</c> is <see langword="true"/>. All
/// other names will not collide with any other in <paramref name="names"/> and will all
/// return <see langword="true"/> for <c>canUse(name)</c>.
/// </summary>
public static void EnsureUniquenessInPlace(
ArrayBuilder<string> names,
ArrayBuilder<bool> isFixed,
Func<string, bool>? canUse = null,
bool isCaseSensitive = true)
{
canUse ??= Functions<string>.True;
using var disposer = ArrayBuilder<int>.GetInstance(out var collisionIndices);
// Don't enumerate as we will be modifying the collection in place.
for (var i = 0; i < names.Count; i++)
{
var name = names[i];
FillCollisionIndices(names, name, isCaseSensitive, collisionIndices);
if (canUse(name) && collisionIndices.Count < 2)
{
// no problems with this parameter name, move onto the next one.
continue;
}
HandleCollisions(names, isFixed, name, canUse, isCaseSensitive, collisionIndices);
}
}
private static void HandleCollisions(
ArrayBuilder<string> names,
ArrayBuilder<bool> isFixed,
string name,
Func<string, bool> canUse,
bool isCaseSensitive,
ArrayBuilder<int> collisionIndices)
{
var suffix = 1;
var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
for (var i = 0; i < collisionIndices.Count; i++)
{
var collisionIndex = collisionIndices[i];
if (isFixed[collisionIndex])
{
// can't do anything about this name.
continue;
}
while (true)
{
var newName = name + suffix++;
if (!names.Contains(newName, comparer) && canUse(newName))
{
// Found a name that doesn't conflict with anything else.
names[collisionIndex] = newName;
break;
}
}
}
}
private static void FillCollisionIndices(
ArrayBuilder<string> names,
string name,
bool isCaseSensitive,
ArrayBuilder<int> collisionIndices)
{
collisionIndices.Clear();
var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
for (int i = 0, n = names.Count; i < n; i++)
{
if (comparer.Equals(names[i], name))
{
collisionIndices.Add(i);
}
}
}
public static string GenerateUniqueName(string baseName, Func<string, bool> canUse)
=> GenerateUniqueName(baseName, string.Empty, canUse);
public static string GenerateUniqueName(string baseName, ISet<string> names, StringComparer comparer)
=> GenerateUniqueName(baseName, x => !names.Contains(x, comparer));
public static string GenerateUniqueName(string baseName, string extension, Func<string, bool> canUse)
{
if (!string.IsNullOrEmpty(extension) && extension[0] != '.')
{
extension = "." + extension;
}
var name = baseName + extension;
var index = 1;
// Check for collisions
while (!canUse(name))
{
name = baseName + index + extension;
index++;
}
return name;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal static class NameGenerator
{
/// <summary>
/// Transforms baseName into a name that does not conflict with any name in 'reservedNames'
/// </summary>
public static string EnsureUniqueness(
string baseName,
IEnumerable<string> reservedNames,
bool isCaseSensitive = true)
{
using var namesDisposer = ArrayBuilder<string>.GetInstance(out var names);
using var isFixedDisposer = ArrayBuilder<bool>.GetInstance(out var isFixed);
using var nameSetDisposer = PooledHashSet<string>.GetInstance(out var nameSet);
names.Add(baseName);
isFixed.Add(false);
foreach (var reservedName in reservedNames)
{
if (nameSet.Add(reservedName))
{
names.Add(reservedName);
isFixed.Add(true);
}
}
EnsureUniquenessInPlace(names, isFixed, isCaseSensitive: isCaseSensitive);
return names.First();
}
public static ImmutableArray<string> EnsureUniqueness(
ImmutableArray<string> names,
Func<string, bool>? canUse = null,
bool isCaseSensitive = true)
{
using var isFixedDisposer = ArrayBuilder<bool>.GetInstance(names.Length, fillWithValue: false, out var isFixed);
var result = ArrayBuilder<string>.GetInstance(names.Length);
result.AddRange(names);
EnsureUniquenessInPlace(result, isFixed, canUse, isCaseSensitive);
return result.ToImmutableAndFree();
}
/// <summary>
/// Ensures that any 'names' is unique and does not collide with any other name. Names that
/// are marked as IsFixed can not be touched. This does mean that if there are two names
/// that are the same, and both are fixed that you will end up with non-unique names at the
/// end.
/// </summary>
public static ImmutableArray<string> EnsureUniqueness(
ImmutableArray<string> names,
ImmutableArray<bool> isFixed,
Func<string, bool>? canUse = null,
bool isCaseSensitive = true)
{
using var isFixedDisposer = ArrayBuilder<bool>.GetInstance(names.Length, out var isFixedBuilder);
isFixedBuilder.AddRange(isFixed);
var result = ArrayBuilder<string>.GetInstance(names.Length);
result.AddRange(names);
EnsureUniquenessInPlace(result, isFixedBuilder, canUse, isCaseSensitive);
return result.ToImmutableAndFree();
}
/// <summary>
/// Updates the names in <paramref name="names"/> to be unique. A name at a particular
/// index <c>i</c> will not be touched if <c>isFixed[i]</c> is <see langword="true"/>. All
/// other names will not collide with any other in <paramref name="names"/> and will all
/// return <see langword="true"/> for <c>canUse(name)</c>.
/// </summary>
public static void EnsureUniquenessInPlace(
ArrayBuilder<string> names,
ArrayBuilder<bool> isFixed,
Func<string, bool>? canUse = null,
bool isCaseSensitive = true)
{
canUse ??= Functions<string>.True;
using var disposer = ArrayBuilder<int>.GetInstance(out var collisionIndices);
// Don't enumerate as we will be modifying the collection in place.
for (var i = 0; i < names.Count; i++)
{
var name = names[i];
FillCollisionIndices(names, name, isCaseSensitive, collisionIndices);
if (canUse(name) && collisionIndices.Count < 2)
{
// no problems with this parameter name, move onto the next one.
continue;
}
HandleCollisions(names, isFixed, name, canUse, isCaseSensitive, collisionIndices);
}
}
private static void HandleCollisions(
ArrayBuilder<string> names,
ArrayBuilder<bool> isFixed,
string name,
Func<string, bool> canUse,
bool isCaseSensitive,
ArrayBuilder<int> collisionIndices)
{
var suffix = 1;
var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
for (var i = 0; i < collisionIndices.Count; i++)
{
var collisionIndex = collisionIndices[i];
if (isFixed[collisionIndex])
{
// can't do anything about this name.
continue;
}
while (true)
{
var newName = name + suffix++;
if (!names.Contains(newName, comparer) && canUse(newName))
{
// Found a name that doesn't conflict with anything else.
names[collisionIndex] = newName;
break;
}
}
}
}
private static void FillCollisionIndices(
ArrayBuilder<string> names,
string name,
bool isCaseSensitive,
ArrayBuilder<int> collisionIndices)
{
collisionIndices.Clear();
var comparer = isCaseSensitive ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase;
for (int i = 0, n = names.Count; i < n; i++)
{
if (comparer.Equals(names[i], name))
{
collisionIndices.Add(i);
}
}
}
public static string GenerateUniqueName(string baseName, Func<string, bool> canUse)
=> GenerateUniqueName(baseName, string.Empty, canUse);
public static string GenerateUniqueName(string baseName, ISet<string> names, StringComparer comparer)
=> GenerateUniqueName(baseName, x => !names.Contains(x, comparer));
public static string GenerateUniqueName(string baseName, string extension, Func<string, bool> canUse)
{
if (!string.IsNullOrEmpty(extension) && extension[0] != '.')
{
extension = "." + extension;
}
var name = baseName + extension;
var index = 1;
// Check for collisions
while (!canUse(name))
{
name = baseName + index + extension;
index++;
}
return name;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Portable/Symbols/AnonymousTypes/SynthesizedSymbols/AnonymousType.PropertySymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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 Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class AnonymousTypeManager
{
/// <summary>
/// Represents an anonymous type template's property symbol.
/// </summary>
internal sealed class AnonymousTypePropertySymbol : PropertySymbol
{
private readonly NamedTypeSymbol _containingType;
private readonly TypeWithAnnotations _typeWithAnnotations;
private readonly string _name;
private readonly int _index;
private readonly ImmutableArray<Location> _locations;
private readonly AnonymousTypePropertyGetAccessorSymbol _getMethod;
private readonly FieldSymbol _backingField;
internal AnonymousTypePropertySymbol(AnonymousTypeTemplateSymbol container, AnonymousTypeField field, TypeWithAnnotations fieldTypeWithAnnotations, int index) :
this(container, field, fieldTypeWithAnnotations, index, ImmutableArray<Location>.Empty, includeBackingField: true)
{
}
internal AnonymousTypePropertySymbol(AnonymousTypePublicSymbol container, AnonymousTypeField field, int index) :
this(container, field, field.TypeWithAnnotations, index, ImmutableArray.Create<Location>(field.Location), includeBackingField: false)
{
}
private AnonymousTypePropertySymbol(
NamedTypeSymbol container,
AnonymousTypeField field,
TypeWithAnnotations fieldTypeWithAnnotations,
int index,
ImmutableArray<Location> locations,
bool includeBackingField)
{
Debug.Assert((object)container != null);
Debug.Assert((object)field != null);
Debug.Assert(fieldTypeWithAnnotations.HasType);
Debug.Assert(index >= 0);
Debug.Assert(!locations.IsDefault);
_containingType = container;
_typeWithAnnotations = fieldTypeWithAnnotations;
_name = field.Name;
_index = index;
_locations = locations;
_getMethod = new AnonymousTypePropertyGetAccessorSymbol(this);
_backingField = includeBackingField ? new AnonymousTypeFieldSymbol(this) : null;
}
internal override int? MemberIndexOpt => _index;
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _typeWithAnnotations; }
}
public override string Name
{
get { return _name; }
}
internal override bool HasSpecialName
{
get { return false; }
}
public override bool IsImplicitlyDeclared
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return GetDeclaringSyntaxReferenceHelper<AnonymousObjectMemberDeclaratorSyntax>(this.Locations);
}
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsIndexer
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override MethodSymbol SetMethod
{
get { return null; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override Microsoft.Cci.CallingConvention CallingConvention
{
get { return Microsoft.Cci.CallingConvention.HasThis; }
}
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<PropertySymbol>.Empty; }
}
public override Symbol ContainingSymbol
{
get { return _containingType; }
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Public; }
}
internal override bool MustCallMethodsDirectly
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override MethodSymbol GetMethod
{
get { return _getMethod; }
}
public FieldSymbol BackingField
{
get { return _backingField; }
}
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == null)
{
return false;
}
else if (ReferenceEquals(this, obj))
{
return true;
}
var other = obj as AnonymousTypePropertySymbol;
if ((object)other == null)
{
return false;
}
// consider properties the same is the owning types are the same and
// the names are equal
return ((object)other != null) && other.Name == this.Name
&& other.ContainingType.Equals(this.ContainingType, compareKind);
}
public override int GetHashCode()
{
return Hash.Combine(this.ContainingType.GetHashCode(), this.Name.GetHashCode());
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Diagnostics;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed partial class AnonymousTypeManager
{
/// <summary>
/// Represents an anonymous type template's property symbol.
/// </summary>
internal sealed class AnonymousTypePropertySymbol : PropertySymbol
{
private readonly NamedTypeSymbol _containingType;
private readonly TypeWithAnnotations _typeWithAnnotations;
private readonly string _name;
private readonly int _index;
private readonly ImmutableArray<Location> _locations;
private readonly AnonymousTypePropertyGetAccessorSymbol _getMethod;
private readonly FieldSymbol _backingField;
internal AnonymousTypePropertySymbol(AnonymousTypeTemplateSymbol container, AnonymousTypeField field, TypeWithAnnotations fieldTypeWithAnnotations, int index) :
this(container, field, fieldTypeWithAnnotations, index, ImmutableArray<Location>.Empty, includeBackingField: true)
{
}
internal AnonymousTypePropertySymbol(AnonymousTypePublicSymbol container, AnonymousTypeField field, int index) :
this(container, field, field.TypeWithAnnotations, index, ImmutableArray.Create<Location>(field.Location), includeBackingField: false)
{
}
private AnonymousTypePropertySymbol(
NamedTypeSymbol container,
AnonymousTypeField field,
TypeWithAnnotations fieldTypeWithAnnotations,
int index,
ImmutableArray<Location> locations,
bool includeBackingField)
{
Debug.Assert((object)container != null);
Debug.Assert((object)field != null);
Debug.Assert(fieldTypeWithAnnotations.HasType);
Debug.Assert(index >= 0);
Debug.Assert(!locations.IsDefault);
_containingType = container;
_typeWithAnnotations = fieldTypeWithAnnotations;
_name = field.Name;
_index = index;
_locations = locations;
_getMethod = new AnonymousTypePropertyGetAccessorSymbol(this);
_backingField = includeBackingField ? new AnonymousTypeFieldSymbol(this) : null;
}
internal override int? MemberIndexOpt => _index;
public override RefKind RefKind
{
get { return RefKind.None; }
}
public override TypeWithAnnotations TypeWithAnnotations
{
get { return _typeWithAnnotations; }
}
public override string Name
{
get { return _name; }
}
internal override bool HasSpecialName
{
get { return false; }
}
public override bool IsImplicitlyDeclared
{
get { return false; }
}
public override ImmutableArray<Location> Locations
{
get { return _locations; }
}
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences
{
get
{
return GetDeclaringSyntaxReferenceHelper<AnonymousObjectMemberDeclaratorSyntax>(this.Locations);
}
}
public override bool IsStatic
{
get { return false; }
}
public override bool IsOverride
{
get { return false; }
}
public override bool IsVirtual
{
get { return false; }
}
public override bool IsIndexer
{
get { return false; }
}
public override bool IsSealed
{
get { return false; }
}
public override bool IsAbstract
{
get { return false; }
}
internal sealed override ObsoleteAttributeData ObsoleteAttributeData
{
get { return null; }
}
public override ImmutableArray<ParameterSymbol> Parameters
{
get { return ImmutableArray<ParameterSymbol>.Empty; }
}
public override MethodSymbol SetMethod
{
get { return null; }
}
public override ImmutableArray<CustomModifier> RefCustomModifiers
{
get { return ImmutableArray<CustomModifier>.Empty; }
}
internal override Microsoft.Cci.CallingConvention CallingConvention
{
get { return Microsoft.Cci.CallingConvention.HasThis; }
}
public override ImmutableArray<PropertySymbol> ExplicitInterfaceImplementations
{
get { return ImmutableArray<PropertySymbol>.Empty; }
}
public override Symbol ContainingSymbol
{
get { return _containingType; }
}
public override NamedTypeSymbol ContainingType
{
get
{
return _containingType;
}
}
public override Accessibility DeclaredAccessibility
{
get { return Accessibility.Public; }
}
internal override bool MustCallMethodsDirectly
{
get { return false; }
}
public override bool IsExtern
{
get { return false; }
}
public override MethodSymbol GetMethod
{
get { return _getMethod; }
}
public FieldSymbol BackingField
{
get { return _backingField; }
}
public override bool Equals(Symbol obj, TypeCompareKind compareKind)
{
if (obj == null)
{
return false;
}
else if (ReferenceEquals(this, obj))
{
return true;
}
var other = obj as AnonymousTypePropertySymbol;
if ((object)other == null)
{
return false;
}
// consider properties the same is the owning types are the same and
// the names are equal
return ((object)other != null) && other.Name == this.Name
&& other.ContainingType.Equals(this.ContainingType, compareKind);
}
public override int GetHashCode()
{
return Hash.Combine(this.ContainingType.GetHashCode(), this.Name.GetHashCode());
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/Core/Shared/Extensions/ITextBufferExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextBufferExtensions
{
internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option2<bool> option)
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option);
}
return option.DefaultValue;
}
internal static T GetFeatureOnOffOption<T>(this ITextBuffer buffer, PerLanguageOption2<T> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool? GetOptionalFeatureOnOffOption(this ITextBuffer buffer, PerLanguageOption2<bool?> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool IsInLspEditorContext(this ITextBuffer buffer)
{
if (buffer.TryGetWorkspace(out var workspace))
{
var workspaceContextService = workspace.Services.GetRequiredService<IWorkspaceContextService>();
return workspaceContextService.IsInLspEditorContext();
}
return false;
}
internal static bool TryGetWorkspace(this ITextBuffer buffer, [NotNullWhen(true)] out Workspace? workspace)
=> Workspace.TryGetWorkspace(buffer.AsTextContainer(), out workspace);
/// <summary>
/// Checks if a buffer supports refactorings.
/// </summary>
internal static bool SupportsRefactorings(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRefactorings(buffer);
/// <summary>
/// Checks if a buffer supports rename.
/// </summary>
internal static bool SupportsRename(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRename(buffer);
/// <summary>
/// Checks if a buffer supports code fixes.
/// </summary>
internal static bool SupportsCodeFixes(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsCodeFixes(buffer);
/// <summary>
/// Checks if a buffer supports navigation.
/// </summary>
internal static bool SupportsNavigationToAnyPosition(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsNavigationToAnyPosition(buffer);
private static bool TryGetSupportsFeatureService(ITextBuffer buffer, [NotNullWhen(true)] out ITextBufferSupportsFeatureService? service)
{
service = null;
if (buffer.TryGetWorkspace(out var workspace))
{
service = workspace.Services.GetService<ITextBufferSupportsFeatureService>();
}
return service != null;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions
{
internal static partial class ITextBufferExtensions
{
internal static bool GetFeatureOnOffOption(this ITextBuffer buffer, Option2<bool> option)
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option);
}
return option.DefaultValue;
}
internal static T GetFeatureOnOffOption<T>(this ITextBuffer buffer, PerLanguageOption2<T> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool? GetOptionalFeatureOnOffOption(this ITextBuffer buffer, PerLanguageOption2<bool?> option)
{
// Add a FailFast to help diagnose 984249. Hopefully this will let us know what the issue is.
try
{
var document = buffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document != null)
{
return document.Project.Solution.Options.GetOption(option, document.Project.Language);
}
return option.DefaultValue;
}
catch (Exception e) when (FatalError.ReportAndPropagate(e))
{
throw ExceptionUtilities.Unreachable;
}
}
internal static bool IsInLspEditorContext(this ITextBuffer buffer)
{
if (buffer.TryGetWorkspace(out var workspace))
{
var workspaceContextService = workspace.Services.GetRequiredService<IWorkspaceContextService>();
return workspaceContextService.IsInLspEditorContext();
}
return false;
}
internal static bool TryGetWorkspace(this ITextBuffer buffer, [NotNullWhen(true)] out Workspace? workspace)
=> Workspace.TryGetWorkspace(buffer.AsTextContainer(), out workspace);
/// <summary>
/// Checks if a buffer supports refactorings.
/// </summary>
internal static bool SupportsRefactorings(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRefactorings(buffer);
/// <summary>
/// Checks if a buffer supports rename.
/// </summary>
internal static bool SupportsRename(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsRename(buffer);
/// <summary>
/// Checks if a buffer supports code fixes.
/// </summary>
internal static bool SupportsCodeFixes(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsCodeFixes(buffer);
/// <summary>
/// Checks if a buffer supports navigation.
/// </summary>
internal static bool SupportsNavigationToAnyPosition(this ITextBuffer buffer)
=> TryGetSupportsFeatureService(buffer, out var service) && service.SupportsNavigationToAnyPosition(buffer);
private static bool TryGetSupportsFeatureService(ITextBuffer buffer, [NotNullWhen(true)] out ITextBufferSupportsFeatureService? service)
{
service = null;
if (buffer.TryGetWorkspace(out var workspace))
{
service = workspace.Services.GetService<ITextBufferSupportsFeatureService>();
}
return service != null;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Analyzers/VisualBasic/Analyzers/RemoveUnnecessaryByVal/VisualBasicRemoveUnnecessaryByValDiagnosticAnalyzer.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryByVal
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicRemoveUnnecessaryByValDiagnosticAnalyzer
Inherits AbstractBuiltInCodeStyleDiagnosticAnalyzer
Public Sub New()
MyBase.New(
diagnosticId:=IDEDiagnosticIds.RemoveUnnecessaryByValDiagnosticId,
enforceOnBuild:=EnforceOnBuildValues.RemoveUnnecessaryByVal,
[option]:=Nothing,
title:=New LocalizableResourceString(NameOf(VisualBasicAnalyzersResources.Remove_ByVal), VisualBasicAnalyzersResources.ResourceManager, GetType(VisualBasicAnalyzersResources)),
isUnnecessary:=True)
End Sub
Protected Overrides Sub InitializeWorker(context As AnalysisContext)
context.RegisterSyntaxNodeAction(
Sub(syntaxContext As SyntaxNodeAnalysisContext)
Dim parameterSyntax = DirectCast(syntaxContext.Node, ParameterSyntax)
For Each modifier In parameterSyntax.Modifiers
If modifier.IsKind(SyntaxKind.ByValKeyword) Then
syntaxContext.ReportDiagnostic(Diagnostic.Create(Descriptor, modifier.GetLocation(), additionalLocations:={parameterSyntax.GetLocation()}))
End If
Next
End Sub, SyntaxKind.Parameter)
End Sub
Public Overrides Function GetAnalyzerCategory() As DiagnosticAnalyzerCategory
Return DiagnosticAnalyzerCategory.SemanticSpanAnalysis
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeStyle
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.RemoveUnnecessaryByVal
<DiagnosticAnalyzer(LanguageNames.VisualBasic)>
Friend NotInheritable Class VisualBasicRemoveUnnecessaryByValDiagnosticAnalyzer
Inherits AbstractBuiltInCodeStyleDiagnosticAnalyzer
Public Sub New()
MyBase.New(
diagnosticId:=IDEDiagnosticIds.RemoveUnnecessaryByValDiagnosticId,
enforceOnBuild:=EnforceOnBuildValues.RemoveUnnecessaryByVal,
[option]:=Nothing,
title:=New LocalizableResourceString(NameOf(VisualBasicAnalyzersResources.Remove_ByVal), VisualBasicAnalyzersResources.ResourceManager, GetType(VisualBasicAnalyzersResources)),
isUnnecessary:=True)
End Sub
Protected Overrides Sub InitializeWorker(context As AnalysisContext)
context.RegisterSyntaxNodeAction(
Sub(syntaxContext As SyntaxNodeAnalysisContext)
Dim parameterSyntax = DirectCast(syntaxContext.Node, ParameterSyntax)
For Each modifier In parameterSyntax.Modifiers
If modifier.IsKind(SyntaxKind.ByValKeyword) Then
syntaxContext.ReportDiagnostic(Diagnostic.Create(Descriptor, modifier.GetLocation(), additionalLocations:={parameterSyntax.GetLocation()}))
End If
Next
End Sub, SyntaxKind.Parameter)
End Sub
Public Overrides Function GetAnalyzerCategory() As DiagnosticAnalyzerCategory
Return DiagnosticAnalyzerCategory.SemanticSpanAnalysis
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/CSharpTest/Diagnostics/RemoveAsyncModifier/RemoveAsyncModifierTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveAsyncModifier
{
using VerifyCS = Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
EmptyDiagnosticAnalyzer,
CodeAnalysis.CSharp.RemoveAsyncModifier.CSharpRemoveAsyncModifierCodeFixProvider>;
public class RemoveAsyncModifierTests : CodeAnalysis.CSharp.Test.Utilities.CSharpTestBase
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_MultipleAndNested()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System;
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (DateTime.Now.Ticks > 0)
{
return;
}
}
async Task {|CS1998:Foo|}()
{
Console.WriteLine(1);
}
async Task {|CS1998:Bar|}()
{
async Task {|CS1998:Baz|}()
{
Func<Task<int>> g = async () {|CS1998:=>|} 5;
}
}
async Task<string> {|CS1998:Tur|}()
{
async Task<string> {|CS1998:Duck|}()
{
async Task<string> {|CS1998:En|}()
{
return ""Developers!"";
}
return ""Developers! Developers!"";
}
return ""Developers! Developers! Developers!"";
}
async Task {|CS1998:Nurk|}()
{
Func<Task<int>> f = async () {|CS1998:=>|} 4;
if (DateTime.Now.Ticks > f().Result)
{
}
}
}",
@"
using System;
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
Task Foo()
{
Console.WriteLine(1);
return Task.CompletedTask;
}
Task Bar()
{
Task Baz()
{
Func<Task<int>> g = () => Task.FromResult(5);
return Task.CompletedTask;
}
return Task.CompletedTask;
}
Task<string> Tur()
{
Task<string> Duck()
{
Task<string> En()
{
return Task.FromResult(""Developers!"");
}
return Task.FromResult(""Developers! Developers!"");
}
return Task.FromResult(""Developers! Developers! Developers!"");
}
Task Nurk()
{
Func<Task<int>> f = () => Task.FromResult(4);
if (DateTime.Now.Ticks > f().Result)
{
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_EmptyBlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}(){}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTask_BlockBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return new ValueTask();
}
return new ValueTask();
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTaskOfT_BlockBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask<int> {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return 2;
}
return 3;
}
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask<int> Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return new ValueTask<int>(2);
}
return new ValueTask<int>(3);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTask_ExpressionBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask {|CS1998:Goo|}() => System.Console.WriteLine(1);
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask Goo()
{
System.Console.WriteLine(1);
return new ValueTask();
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTaskOfT_ExpressionBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask<int> {|CS1998:Goo|}() => 3;
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask<int> Goo() => new ValueTask<int>(3);
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_Throws()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
throw new System.ApplicationException();
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
throw new System.ApplicationException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_WithLocalFunction()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (GetTicks() > 0)
{
return;
}
long GetTicks()
{
return System.DateTime.Now.Ticks;
}
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (GetTicks() > 0)
{
return Task.CompletedTask;
}
long GetTicks()
{
return System.DateTime.Now.Ticks;
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_WithLambda()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
System.Func<long> getTicks = () => {
return System.DateTime.Now.Ticks;
};
if (getTicks() > 0)
{
return;
}
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
System.Func<long> getTicks = () => {
return System.DateTime.Now.Ticks;
};
if (getTicks() > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task<int> {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return 2;
}
return 3;
}
}",
@"
using System.Threading.Tasks;
class C
{
Task<int> Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.FromResult(2);
}
return Task.FromResult(3);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task<int> {|CS1998:Goo|}() => 2;
}",
@"
using System.Threading.Tasks;
class C
{
Task<int> Goo() => Task.FromResult(2);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System;
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}() => Console.WriteLine(""Hello"");
}",
@"
using System;
using System.Threading.Tasks;
class C
{
Task Goo()
{
Console.WriteLine(""Hello"");
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System.Threading.Tasks;
class C
{
public void M1()
{
async Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}
}",
@"using System.Threading.Tasks;
class C
{
public void M1()
{
Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
async Task {|CS1998:Goo|}() => Console.WriteLine(1);
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Task Goo() { Console.WriteLine(1); return Task.CompletedTask; }
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System.Threading.Tasks;
class C
{
public void M1()
{
async Task<int> {|CS1998:Goo|}()
{
return 1;
}
}
}",
@"using System.Threading.Tasks;
class C
{
public void M1()
{
Task<int> Goo()
{
return Task.FromResult(1);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System.Threading.Tasks;
class C
{
public void M1()
{
async Task<int> {|CS1998:Goo|}() => 1;
}
}",
@"using System.Threading.Tasks;
class C
{
public void M1()
{
Task<int> Goo() => Task.FromResult(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task AnonymousFunction_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = (Func<Task>)async {|CS1998:delegate|} {
if (System.DateTime.Now.Ticks > 0)
{
return;
}
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = (Func<Task>)delegate
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task AnonymousFunction_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = (Func<Task<int>>)async {|CS1998:delegate|}
{
return 1;
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = (Func<Task<int>>)delegate
{
return Task.FromResult(1);
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = async x {|CS1998:=>|} 1;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = x => Task.FromResult(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = async x {|CS1998:=>|} {
return 1;
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = x =>
{
return Task.FromResult(1);
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = async x {|CS1998:=>|} Console.WriteLine(1);
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = x => { Console.WriteLine(1); return Task.CompletedTask; };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = async x {|CS1998:=>|}
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = x => {
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = async () {|CS1998:=>|} 1;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = () => Task.FromResult(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = async () {|CS1998:=>|} {
return 1;
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = () =>
{
return Task.FromResult(1);
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = async () {|CS1998:=>|} Console.WriteLine(1);
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = () => { Console.WriteLine(1); return Task.CompletedTask; };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = async () {|CS1998:=>|}
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = () => {
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_FullyQualified()
{
await VerifyCS.VerifyCodeFixAsync(
@"
class C
{
async System.Threading.Tasks.Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}",
@"
class C
{
System.Threading.Tasks.Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return System.Threading.Tasks.Task.CompletedTask;
}
return System.Threading.Tasks.Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_TaskOfT_BlockBody_FullyQualified()
{
await VerifyCS.VerifyCodeFixAsync(
@"
class C
{
async System.Threading.Tasks.Task<int> {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return 1;
}
return 2;
}
}",
@"
class C
{
System.Threading.Tasks.Task<int> Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return System.Threading.Tasks.Task.FromResult(1);
}
return System.Threading.Tasks.Task.FromResult(2);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task IAsyncEnumerable_Missing()
{
var source = @"
using System.Threading.Tasks;
using System.Collections.Generic;
class C
{
async IAsyncEnumerable<int> M()
{
yield return 1;
}
}" + AsyncStreamsTypes;
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(7,33): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(7, 33, 7, 34),
},
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_AsyncVoid_Missing()
{
var source = @"
using System.Threading.Tasks;
class C
{
async void M()
{
System.Console.WriteLine(1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(6,16): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(6, 16, 6, 17),
},
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_AsyncVoid_Missing()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
void M()
{
Action a = async () => Console.WriteLine(1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(9,29): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(9, 29, 9, 31),
},
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_AsyncVoid_Missing()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
void M()
{
Action<int> a = async x => Console.WriteLine(x);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(9,33): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(9, 33, 9, 35),
},
FixedCode = source,
}.RunAsync();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.RemoveAsyncModifier
{
using VerifyCS = Editor.UnitTests.CodeActions.CSharpCodeFixVerifier<
EmptyDiagnosticAnalyzer,
CodeAnalysis.CSharp.RemoveAsyncModifier.CSharpRemoveAsyncModifierCodeFixProvider>;
public class RemoveAsyncModifierTests : CodeAnalysis.CSharp.Test.Utilities.CSharpTestBase
{
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_MultipleAndNested()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System;
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (DateTime.Now.Ticks > 0)
{
return;
}
}
async Task {|CS1998:Foo|}()
{
Console.WriteLine(1);
}
async Task {|CS1998:Bar|}()
{
async Task {|CS1998:Baz|}()
{
Func<Task<int>> g = async () {|CS1998:=>|} 5;
}
}
async Task<string> {|CS1998:Tur|}()
{
async Task<string> {|CS1998:Duck|}()
{
async Task<string> {|CS1998:En|}()
{
return ""Developers!"";
}
return ""Developers! Developers!"";
}
return ""Developers! Developers! Developers!"";
}
async Task {|CS1998:Nurk|}()
{
Func<Task<int>> f = async () {|CS1998:=>|} 4;
if (DateTime.Now.Ticks > f().Result)
{
}
}
}",
@"
using System;
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
Task Foo()
{
Console.WriteLine(1);
return Task.CompletedTask;
}
Task Bar()
{
Task Baz()
{
Func<Task<int>> g = () => Task.FromResult(5);
return Task.CompletedTask;
}
return Task.CompletedTask;
}
Task<string> Tur()
{
Task<string> Duck()
{
Task<string> En()
{
return Task.FromResult(""Developers!"");
}
return Task.FromResult(""Developers! Developers!"");
}
return Task.FromResult(""Developers! Developers! Developers!"");
}
Task Nurk()
{
Func<Task<int>> f = () => Task.FromResult(4);
if (DateTime.Now.Ticks > f().Result)
{
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_EmptyBlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}(){}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTask_BlockBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return new ValueTask();
}
return new ValueTask();
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTaskOfT_BlockBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask<int> {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return 2;
}
return 3;
}
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask<int> Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return new ValueTask<int>(2);
}
return new ValueTask<int>(3);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTask_ExpressionBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask {|CS1998:Goo|}() => System.Console.WriteLine(1);
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask Goo()
{
System.Console.WriteLine(1);
return new ValueTask();
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_ValueTaskOfT_ExpressionBody()
{
var source = @"
using System.Threading.Tasks;
class C
{
async ValueTask<int> {|CS1998:Goo|}() => 3;
}";
var expected = @"
using System.Threading.Tasks;
class C
{
ValueTask<int> Goo() => new ValueTask<int>(3);
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
FixedCode = expected,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_Throws()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
throw new System.ApplicationException();
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
throw new System.ApplicationException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_WithLocalFunction()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
if (GetTicks() > 0)
{
return;
}
long GetTicks()
{
return System.DateTime.Now.Ticks;
}
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
if (GetTicks() > 0)
{
return Task.CompletedTask;
}
long GetTicks()
{
return System.DateTime.Now.Ticks;
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_WithLambda()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}()
{
System.Func<long> getTicks = () => {
return System.DateTime.Now.Ticks;
};
if (getTicks() > 0)
{
return;
}
}
}",
@"
using System.Threading.Tasks;
class C
{
Task Goo()
{
System.Func<long> getTicks = () => {
return System.DateTime.Now.Ticks;
};
if (getTicks() > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task<int> {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return 2;
}
return 3;
}
}",
@"
using System.Threading.Tasks;
class C
{
Task<int> Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.FromResult(2);
}
return Task.FromResult(3);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System.Threading.Tasks;
class C
{
async Task<int> {|CS1998:Goo|}() => 2;
}",
@"
using System.Threading.Tasks;
class C
{
Task<int> Goo() => Task.FromResult(2);
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"
using System;
using System.Threading.Tasks;
class C
{
async Task {|CS1998:Goo|}() => Console.WriteLine(""Hello"");
}",
@"
using System;
using System.Threading.Tasks;
class C
{
Task Goo()
{
Console.WriteLine(""Hello"");
return Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System.Threading.Tasks;
class C
{
public void M1()
{
async Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}
}",
@"using System.Threading.Tasks;
class C
{
public void M1()
{
Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
async Task {|CS1998:Goo|}() => Console.WriteLine(1);
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Task Goo() { Console.WriteLine(1); return Task.CompletedTask; }
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System.Threading.Tasks;
class C
{
public void M1()
{
async Task<int> {|CS1998:Goo|}()
{
return 1;
}
}
}",
@"using System.Threading.Tasks;
class C
{
public void M1()
{
Task<int> Goo()
{
return Task.FromResult(1);
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task LocalFunction_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System.Threading.Tasks;
class C
{
public void M1()
{
async Task<int> {|CS1998:Goo|}() => 1;
}
}",
@"using System.Threading.Tasks;
class C
{
public void M1()
{
Task<int> Goo() => Task.FromResult(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task AnonymousFunction_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = (Func<Task>)async {|CS1998:delegate|} {
if (System.DateTime.Now.Ticks > 0)
{
return;
}
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = (Func<Task>)delegate
{
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task AnonymousFunction_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = (Func<Task<int>>)async {|CS1998:delegate|}
{
return 1;
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = (Func<Task<int>>)delegate
{
return Task.FromResult(1);
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = async x {|CS1998:=>|} 1;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = x => Task.FromResult(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = async x {|CS1998:=>|} {
return 1;
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task<int>> foo = x =>
{
return Task.FromResult(1);
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = async x {|CS1998:=>|} Console.WriteLine(1);
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = x => { Console.WriteLine(1); return Task.CompletedTask; };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = async x {|CS1998:=>|}
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<int, Task> foo = x => {
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_TaskOfT_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = async () {|CS1998:=>|} 1;
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = () => Task.FromResult(1);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_TaskOfT_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = async () {|CS1998:=>|} {
return 1;
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task<int>> foo = () =>
{
return Task.FromResult(1);
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_Task_ExpressionBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = async () {|CS1998:=>|} Console.WriteLine(1);
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = () => { Console.WriteLine(1); return Task.CompletedTask; };
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_Task_BlockBody()
{
await VerifyCS.VerifyCodeFixAsync(
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = async () {|CS1998:=>|}
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
};
}
}",
@"using System;
using System.Threading.Tasks;
class C
{
public void M1()
{
Func<Task> foo = () => {
if (System.DateTime.Now.Ticks > 0)
{
return Task.CompletedTask;
}
return Task.CompletedTask;
};
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_Task_BlockBody_FullyQualified()
{
await VerifyCS.VerifyCodeFixAsync(
@"
class C
{
async System.Threading.Tasks.Task {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return;
}
}
}",
@"
class C
{
System.Threading.Tasks.Task Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return System.Threading.Tasks.Task.CompletedTask;
}
return System.Threading.Tasks.Task.CompletedTask;
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_TaskOfT_BlockBody_FullyQualified()
{
await VerifyCS.VerifyCodeFixAsync(
@"
class C
{
async System.Threading.Tasks.Task<int> {|CS1998:Goo|}()
{
if (System.DateTime.Now.Ticks > 0)
{
return 1;
}
return 2;
}
}",
@"
class C
{
System.Threading.Tasks.Task<int> Goo()
{
if (System.DateTime.Now.Ticks > 0)
{
return System.Threading.Tasks.Task.FromResult(1);
}
return System.Threading.Tasks.Task.FromResult(2);
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task IAsyncEnumerable_Missing()
{
var source = @"
using System.Threading.Tasks;
using System.Collections.Generic;
class C
{
async IAsyncEnumerable<int> M()
{
yield return 1;
}
}" + AsyncStreamsTypes;
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(7,33): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(7, 33, 7, 34),
},
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task Method_AsyncVoid_Missing()
{
var source = @"
using System.Threading.Tasks;
class C
{
async void M()
{
System.Console.WriteLine(1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(6,16): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(6, 16, 6, 17),
},
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task ParenthesisedLambda_AsyncVoid_Missing()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
void M()
{
Action a = async () => Console.WriteLine(1);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(9,29): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(9, 29, 9, 31),
},
FixedCode = source,
}.RunAsync();
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveAsyncModifier)]
public async Task SimpleLambda_AsyncVoid_Missing()
{
var source = @"
using System;
using System.Threading.Tasks;
class C
{
void M()
{
Action<int> a = async x => Console.WriteLine(x);
}
}";
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard21,
TestCode = source,
ExpectedDiagnostics =
{
// /0/Test0.cs(9,33): 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.
DiagnosticResult.CompilerWarning("CS1998").WithSpan(9, 33, 9, 35),
},
FixedCode = source,
}.RunAsync();
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/Core/Portable/Symbols/Attributes/CommonFieldEarlyWellKnownAttributeData.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from early well-known custom attributes applied on a field.
/// </summary>
internal class CommonFieldEarlyWellKnownAttributeData : EarlyWellKnownAttributeData
{
#region ObsoleteAttribute
private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized;
public ObsoleteAttributeData ObsoleteAttributeData
{
get
{
VerifySealed(expected: true);
return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData;
}
set
{
VerifySealed(expected: false);
Debug.Assert(value != null);
Debug.Assert(!value.IsUninitialized);
_obsoleteAttributeData = value;
SetDataStored();
}
}
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Information decoded from early well-known custom attributes applied on a field.
/// </summary>
internal class CommonFieldEarlyWellKnownAttributeData : EarlyWellKnownAttributeData
{
#region ObsoleteAttribute
private ObsoleteAttributeData _obsoleteAttributeData = ObsoleteAttributeData.Uninitialized;
public ObsoleteAttributeData ObsoleteAttributeData
{
get
{
VerifySealed(expected: true);
return _obsoleteAttributeData.IsUninitialized ? null : _obsoleteAttributeData;
}
set
{
VerifySealed(expected: false);
Debug.Assert(value != null);
Debug.Assert(!value.IsUninitialized);
_obsoleteAttributeData = value;
SetDataStored();
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/Core/Tagging/TaggerTextChangeBehavior.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
/// <summary>
/// Flags that affect how the tagger infrastructure responds to text changes.
/// </summary>
[Flags]
internal enum TaggerTextChangeBehavior
{
/// <summary>
/// The async tagger infrastructure will not track any text changes and will not do
/// anything special in the presence of them.
/// </summary>
None = 0,
/// <summary>
/// The async tagger infrastructure will track text changes to the subject buffer it is
/// attached to. The text changes will be provided to the <see cref="TaggerContext{TTag}"/>
/// that is passed to <see cref="AbstractAsynchronousTaggerProvider{TTag}.ProduceTagsAsync(TaggerContext{TTag})"/>.
/// </summary>
TrackTextChanges = 1 << 0,
/// <summary>
/// The async tagger infrastructure will track text changes to the subject buffer it is
/// attached to. The text changes will be provided to the <see cref="TaggerContext{TTag}"/>
/// that is passed to <see cref="AbstractAsynchronousTaggerProvider{TTag}.ProduceTagsAsync(TaggerContext{TTag})"/>.
///
/// On any edit, tags that intersect the text change range will immediately removed.
/// </summary>
RemoveTagsThatIntersectEdits = TrackTextChanges | (1 << 1),
/// <summary>
/// The async tagger infrastructure will track text changes to the subject buffer it is
/// attached to.
///
/// On any edit all tags will we be removed.
/// </summary>
RemoveAllTags = TrackTextChanges | (1 << 2),
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Editor.Tagging
{
/// <summary>
/// Flags that affect how the tagger infrastructure responds to text changes.
/// </summary>
[Flags]
internal enum TaggerTextChangeBehavior
{
/// <summary>
/// The async tagger infrastructure will not track any text changes and will not do
/// anything special in the presence of them.
/// </summary>
None = 0,
/// <summary>
/// The async tagger infrastructure will track text changes to the subject buffer it is
/// attached to. The text changes will be provided to the <see cref="TaggerContext{TTag}"/>
/// that is passed to <see cref="AbstractAsynchronousTaggerProvider{TTag}.ProduceTagsAsync(TaggerContext{TTag})"/>.
/// </summary>
TrackTextChanges = 1 << 0,
/// <summary>
/// The async tagger infrastructure will track text changes to the subject buffer it is
/// attached to. The text changes will be provided to the <see cref="TaggerContext{TTag}"/>
/// that is passed to <see cref="AbstractAsynchronousTaggerProvider{TTag}.ProduceTagsAsync(TaggerContext{TTag})"/>.
///
/// On any edit, tags that intersect the text change range will immediately removed.
/// </summary>
RemoveTagsThatIntersectEdits = TrackTextChanges | (1 << 1),
/// <summary>
/// The async tagger infrastructure will track text changes to the subject buffer it is
/// attached to.
///
/// On any edit all tags will we be removed.
/// </summary>
RemoveAllTags = TrackTextChanges | (1 << 2),
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Tools/AnalyzerRunner/app.config | <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<gcServer enabled="true" />
<appDomainManagerType value="Microsoft.SourceBrowser.Common.CustomAppDomainManager"/>
<appDomainManagerAssembly value="Microsoft.SourceBrowser.Common"/>
</runtime>
</configuration>
| <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<runtime>
<gcServer enabled="true" />
<appDomainManagerType value="Microsoft.SourceBrowser.Common.CustomAppDomainManager"/>
<appDomainManagerAssembly value="Microsoft.SourceBrowser.Common"/>
</runtime>
</configuration>
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/Core/Portable/PEWriter/FullMetadataWriter.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
internal sealed class FullMetadataWriter : MetadataWriter
{
private readonly DefinitionIndex<ITypeDefinition> _typeDefs;
private readonly DefinitionIndex<IEventDefinition> _eventDefs;
private readonly DefinitionIndex<IFieldDefinition> _fieldDefs;
private readonly DefinitionIndex<IMethodDefinition> _methodDefs;
private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs;
private readonly DefinitionIndex<IParameterDefinition> _parameterDefs;
private readonly DefinitionIndex<IGenericParameter> _genericParameters;
private readonly Dictionary<ITypeDefinition, int> _fieldDefIndex;
private readonly Dictionary<ITypeDefinition, int> _methodDefIndex;
private readonly Dictionary<IMethodDefinition, int> _parameterListIndex;
private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex;
private readonly HeapOrReferenceIndex<string> _moduleRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex;
private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex;
private readonly TypeReferenceIndex _typeRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex;
private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex;
public static MetadataWriter Create(
EmitContext context,
CommonMessageProvider messageProvider,
bool metadataOnly,
bool deterministic,
bool emitTestCoverageData,
bool hasPdbStream,
CancellationToken cancellationToken)
{
var builder = new MetadataBuilder();
MetadataBuilder? debugBuilderOpt;
switch (context.Module.DebugInformationFormat)
{
case DebugInformationFormat.PortablePdb:
debugBuilderOpt = hasPdbStream ? new MetadataBuilder() : null;
break;
case DebugInformationFormat.Embedded:
debugBuilderOpt = metadataOnly ? null : new MetadataBuilder();
break;
default:
debugBuilderOpt = null;
break;
}
var dynamicAnalysisDataWriterOpt = emitTestCoverageData ?
new DynamicAnalysisDataWriter(context.Module.DebugDocumentCount, context.Module.HintNumberOfMethodDefinitions) :
null;
return new FullMetadataWriter(context, builder, debugBuilderOpt, dynamicAnalysisDataWriterOpt, messageProvider, metadataOnly, deterministic,
emitTestCoverageData, cancellationToken);
}
private FullMetadataWriter(
EmitContext context,
MetadataBuilder builder,
MetadataBuilder? debugBuilderOpt,
DynamicAnalysisDataWriter? dynamicAnalysisDataWriterOpt,
CommonMessageProvider messageProvider,
bool metadataOnly,
bool deterministic,
bool emitTestCoverageData,
CancellationToken cancellationToken)
: base(builder, debugBuilderOpt, dynamicAnalysisDataWriterOpt, context, messageProvider, metadataOnly, deterministic,
emitTestCoverageData, cancellationToken)
{
// EDMAURER make some intelligent guesses for the initial sizes of these things.
int numMethods = this.module.HintNumberOfMethodDefinitions;
int numTypeDefsGuess = numMethods / 6;
int numFieldDefsGuess = numTypeDefsGuess * 4;
int numPropertyDefsGuess = numMethods / 4;
_typeDefs = new DefinitionIndex<ITypeDefinition>(numTypeDefsGuess);
_eventDefs = new DefinitionIndex<IEventDefinition>(0);
_fieldDefs = new DefinitionIndex<IFieldDefinition>(numFieldDefsGuess);
_methodDefs = new DefinitionIndex<IMethodDefinition>(numMethods);
_propertyDefs = new DefinitionIndex<IPropertyDefinition>(numPropertyDefsGuess);
_parameterDefs = new DefinitionIndex<IParameterDefinition>(numMethods);
_genericParameters = new DefinitionIndex<IGenericParameter>(0);
_fieldDefIndex = new Dictionary<ITypeDefinition, int>(numTypeDefsGuess, ReferenceEqualityComparer.Instance);
_methodDefIndex = new Dictionary<ITypeDefinition, int>(numTypeDefsGuess, ReferenceEqualityComparer.Instance);
_parameterListIndex = new Dictionary<IMethodDefinition, int>(numMethods, ReferenceEqualityComparer.Instance);
_assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this);
_moduleRefIndex = new HeapOrReferenceIndex<string>(this);
_memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this));
_methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this));
_typeRefIndex = new TypeReferenceIndex(this);
_typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this));
_standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this);
}
protected override ushort Generation
{
get { return 0; }
}
protected override Guid EncId
{
get { return Guid.Empty; }
}
protected override Guid EncBaseId
{
get { return Guid.Empty; }
}
protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle)
{
int index;
bool result = _typeDefs.TryGetValue(def, out index);
handle = MetadataTokens.TypeDefinitionHandle(index);
return result;
}
protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def)
{
return MetadataTokens.TypeDefinitionHandle(_typeDefs[def]);
}
protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle)
{
return _typeDefs[MetadataTokens.GetRowNumber(handle)];
}
protected override IReadOnlyList<ITypeDefinition> GetTypeDefs()
{
return _typeDefs.Rows;
}
protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def)
{
return MetadataTokens.EventDefinitionHandle(_eventDefs[def]);
}
protected override IReadOnlyList<IEventDefinition> GetEventDefs()
{
return _eventDefs.Rows;
}
protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefs[def]);
}
protected override IReadOnlyList<IFieldDefinition> GetFieldDefs()
{
return _fieldDefs.Rows;
}
protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle)
{
int index;
bool result = _methodDefs.TryGetValue(def, out index);
handle = MetadataTokens.MethodDefinitionHandle(index);
return result;
}
protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def)
{
return MetadataTokens.MethodDefinitionHandle(_methodDefs[def]);
}
protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle handle)
{
return _methodDefs[MetadataTokens.GetRowNumber(handle)];
}
protected override IReadOnlyList<IMethodDefinition> GetMethodDefs()
{
return _methodDefs.Rows;
}
protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def)
{
return MetadataTokens.PropertyDefinitionHandle(_propertyDefs[def]);
}
protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs()
{
return _propertyDefs.Rows;
}
protected override ParameterHandle GetParameterHandle(IParameterDefinition def)
{
return MetadataTokens.ParameterHandle(_parameterDefs[def]);
}
protected override IReadOnlyList<IParameterDefinition> GetParameterDefs()
{
return _parameterDefs.Rows;
}
protected override IReadOnlyList<IGenericParameter> GetGenericParameters()
{
return _genericParameters.Rows;
}
protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefIndex[typeDef]);
}
protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef)
{
return MetadataTokens.MethodDefinitionHandle(_methodDefIndex[typeDef]);
}
protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef)
{
return MetadataTokens.ParameterHandle(_parameterListIndex[methodDef]);
}
protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
{
return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(reference.Identity));
}
protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs()
{
return _assemblyRefIndex.Rows;
}
protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference)
{
return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<string> GetModuleRefs()
{
return _moduleRefIndex.Rows;
}
protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference)
{
return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs()
{
return _memberRefIndex.Rows;
}
protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference)
{
return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs()
{
return _methodSpecIndex.Rows;
}
protected override int GreatestMethodDefIndex => _methodDefs.NextRowId;
protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle)
{
int index;
bool result = _typeRefIndex.TryGetValue(reference, out index);
handle = MetadataTokens.TypeReferenceHandle(index);
return result;
}
protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference)
{
return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeRefs()
{
return _typeRefIndex.Rows;
}
protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference)
{
return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeSpecs()
{
return _typeSpecIndex.Rows;
}
protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
{
return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex));
}
protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles()
{
return _standAloneSignatureIndex.Rows;
}
protected override ReferenceIndexer CreateReferenceVisitor()
{
return new FullReferenceIndexer(this);
}
protected override void ReportReferencesToAddedSymbols()
{
// noop
}
private sealed class FullReferenceIndexer : ReferenceIndexer
{
internal FullReferenceIndexer(MetadataWriter metadataWriter)
: base(metadataWriter)
{
}
}
protected override void PopulateEventMapTableRows()
{
ITypeDefinition? lastParent = null;
foreach (IEventDefinition eventDef in this.GetEventDefs())
{
if (eventDef.ContainingTypeDefinition == lastParent)
{
continue;
}
lastParent = eventDef.ContainingTypeDefinition;
metadata.AddEventMap(
declaringType: GetTypeDefinitionHandle(lastParent),
eventList: GetEventDefinitionHandle(eventDef));
}
}
protected override void PopulatePropertyMapTableRows()
{
ITypeDefinition? lastParent = null;
foreach (IPropertyDefinition propertyDef in this.GetPropertyDefs())
{
if (propertyDef.ContainingTypeDefinition == lastParent)
{
continue;
}
lastParent = propertyDef.ContainingTypeDefinition;
metadata.AddPropertyMap(
declaringType: GetTypeDefinitionHandle(lastParent),
propertyList: GetPropertyDefIndex(propertyDef));
}
}
protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef)
{
_typeDefs.Add(typeDef);
IEnumerable<IGenericTypeParameter> typeParameters = this.GetConsolidatedTypeParameters(typeDef);
if (typeParameters != null)
{
foreach (IGenericTypeParameter genericParameter in typeParameters)
{
_genericParameters.Add(genericParameter);
}
}
foreach (MethodImplementation methodImplementation in typeDef.GetExplicitImplementationOverrides(Context))
{
this.methodImplList.Add(methodImplementation);
}
foreach (IEventDefinition eventDef in typeDef.GetEvents(Context))
{
_eventDefs.Add(eventDef);
}
_fieldDefIndex.Add(typeDef, _fieldDefs.NextRowId);
foreach (IFieldDefinition fieldDef in typeDef.GetFields(Context))
{
_fieldDefs.Add(fieldDef);
}
_methodDefIndex.Add(typeDef, _methodDefs.NextRowId);
foreach (IMethodDefinition methodDef in typeDef.GetMethods(Context))
{
this.CreateIndicesFor(methodDef);
_methodDefs.Add(methodDef);
}
foreach (IPropertyDefinition propertyDef in typeDef.GetProperties(Context))
{
_propertyDefs.Add(propertyDef);
}
}
private void CreateIndicesFor(IMethodDefinition methodDef)
{
_parameterListIndex.Add(methodDef, _parameterDefs.NextRowId);
foreach (var paramDef in this.GetParametersToEmit(methodDef))
{
_parameterDefs.Add(paramDef);
}
if (methodDef.GenericParameterCount > 0)
{
foreach (IGenericMethodParameter genericParameter in methodDef.GenericParameters)
{
_genericParameters.Add(genericParameter);
}
}
}
private struct DefinitionIndex<T> where T : class, IReference
{
// IReference to RowId
private readonly Dictionary<T, int> _index;
private readonly List<T> _rows;
public DefinitionIndex(int capacity)
{
_index = new Dictionary<T, int>(capacity, ReferenceEqualityComparer.Instance);
_rows = new List<T>(capacity);
}
public bool TryGetValue(T item, out int rowId)
{
return _index.TryGetValue(item, out rowId);
}
public int this[T item]
{
get { return _index[item]; }
}
public T this[int rowId]
{
get { return _rows[rowId - 1]; }
}
public IReadOnlyList<T> Rows
{
get { return _rows; }
}
public int NextRowId
{
get { return _rows.Count + 1; }
}
public void Add(T item)
{
_index.Add(item, NextRowId);
_rows.Add(item);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Utilities;
using EmitContext = Microsoft.CodeAnalysis.Emit.EmitContext;
namespace Microsoft.Cci
{
internal sealed class FullMetadataWriter : MetadataWriter
{
private readonly DefinitionIndex<ITypeDefinition> _typeDefs;
private readonly DefinitionIndex<IEventDefinition> _eventDefs;
private readonly DefinitionIndex<IFieldDefinition> _fieldDefs;
private readonly DefinitionIndex<IMethodDefinition> _methodDefs;
private readonly DefinitionIndex<IPropertyDefinition> _propertyDefs;
private readonly DefinitionIndex<IParameterDefinition> _parameterDefs;
private readonly DefinitionIndex<IGenericParameter> _genericParameters;
private readonly Dictionary<ITypeDefinition, int> _fieldDefIndex;
private readonly Dictionary<ITypeDefinition, int> _methodDefIndex;
private readonly Dictionary<IMethodDefinition, int> _parameterListIndex;
private readonly HeapOrReferenceIndex<AssemblyIdentity> _assemblyRefIndex;
private readonly HeapOrReferenceIndex<string> _moduleRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeMemberReference> _memberRefIndex;
private readonly InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference> _methodSpecIndex;
private readonly TypeReferenceIndex _typeRefIndex;
private readonly InstanceAndStructuralReferenceIndex<ITypeReference> _typeSpecIndex;
private readonly HeapOrReferenceIndex<BlobHandle> _standAloneSignatureIndex;
public static MetadataWriter Create(
EmitContext context,
CommonMessageProvider messageProvider,
bool metadataOnly,
bool deterministic,
bool emitTestCoverageData,
bool hasPdbStream,
CancellationToken cancellationToken)
{
var builder = new MetadataBuilder();
MetadataBuilder? debugBuilderOpt;
switch (context.Module.DebugInformationFormat)
{
case DebugInformationFormat.PortablePdb:
debugBuilderOpt = hasPdbStream ? new MetadataBuilder() : null;
break;
case DebugInformationFormat.Embedded:
debugBuilderOpt = metadataOnly ? null : new MetadataBuilder();
break;
default:
debugBuilderOpt = null;
break;
}
var dynamicAnalysisDataWriterOpt = emitTestCoverageData ?
new DynamicAnalysisDataWriter(context.Module.DebugDocumentCount, context.Module.HintNumberOfMethodDefinitions) :
null;
return new FullMetadataWriter(context, builder, debugBuilderOpt, dynamicAnalysisDataWriterOpt, messageProvider, metadataOnly, deterministic,
emitTestCoverageData, cancellationToken);
}
private FullMetadataWriter(
EmitContext context,
MetadataBuilder builder,
MetadataBuilder? debugBuilderOpt,
DynamicAnalysisDataWriter? dynamicAnalysisDataWriterOpt,
CommonMessageProvider messageProvider,
bool metadataOnly,
bool deterministic,
bool emitTestCoverageData,
CancellationToken cancellationToken)
: base(builder, debugBuilderOpt, dynamicAnalysisDataWriterOpt, context, messageProvider, metadataOnly, deterministic,
emitTestCoverageData, cancellationToken)
{
// EDMAURER make some intelligent guesses for the initial sizes of these things.
int numMethods = this.module.HintNumberOfMethodDefinitions;
int numTypeDefsGuess = numMethods / 6;
int numFieldDefsGuess = numTypeDefsGuess * 4;
int numPropertyDefsGuess = numMethods / 4;
_typeDefs = new DefinitionIndex<ITypeDefinition>(numTypeDefsGuess);
_eventDefs = new DefinitionIndex<IEventDefinition>(0);
_fieldDefs = new DefinitionIndex<IFieldDefinition>(numFieldDefsGuess);
_methodDefs = new DefinitionIndex<IMethodDefinition>(numMethods);
_propertyDefs = new DefinitionIndex<IPropertyDefinition>(numPropertyDefsGuess);
_parameterDefs = new DefinitionIndex<IParameterDefinition>(numMethods);
_genericParameters = new DefinitionIndex<IGenericParameter>(0);
_fieldDefIndex = new Dictionary<ITypeDefinition, int>(numTypeDefsGuess, ReferenceEqualityComparer.Instance);
_methodDefIndex = new Dictionary<ITypeDefinition, int>(numTypeDefsGuess, ReferenceEqualityComparer.Instance);
_parameterListIndex = new Dictionary<IMethodDefinition, int>(numMethods, ReferenceEqualityComparer.Instance);
_assemblyRefIndex = new HeapOrReferenceIndex<AssemblyIdentity>(this);
_moduleRefIndex = new HeapOrReferenceIndex<string>(this);
_memberRefIndex = new InstanceAndStructuralReferenceIndex<ITypeMemberReference>(this, new MemberRefComparer(this));
_methodSpecIndex = new InstanceAndStructuralReferenceIndex<IGenericMethodInstanceReference>(this, new MethodSpecComparer(this));
_typeRefIndex = new TypeReferenceIndex(this);
_typeSpecIndex = new InstanceAndStructuralReferenceIndex<ITypeReference>(this, new TypeSpecComparer(this));
_standAloneSignatureIndex = new HeapOrReferenceIndex<BlobHandle>(this);
}
protected override ushort Generation
{
get { return 0; }
}
protected override Guid EncId
{
get { return Guid.Empty; }
}
protected override Guid EncBaseId
{
get { return Guid.Empty; }
}
protected override bool TryGetTypeDefinitionHandle(ITypeDefinition def, out TypeDefinitionHandle handle)
{
int index;
bool result = _typeDefs.TryGetValue(def, out index);
handle = MetadataTokens.TypeDefinitionHandle(index);
return result;
}
protected override TypeDefinitionHandle GetTypeDefinitionHandle(ITypeDefinition def)
{
return MetadataTokens.TypeDefinitionHandle(_typeDefs[def]);
}
protected override ITypeDefinition GetTypeDef(TypeDefinitionHandle handle)
{
return _typeDefs[MetadataTokens.GetRowNumber(handle)];
}
protected override IReadOnlyList<ITypeDefinition> GetTypeDefs()
{
return _typeDefs.Rows;
}
protected override EventDefinitionHandle GetEventDefinitionHandle(IEventDefinition def)
{
return MetadataTokens.EventDefinitionHandle(_eventDefs[def]);
}
protected override IReadOnlyList<IEventDefinition> GetEventDefs()
{
return _eventDefs.Rows;
}
protected override FieldDefinitionHandle GetFieldDefinitionHandle(IFieldDefinition def)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefs[def]);
}
protected override IReadOnlyList<IFieldDefinition> GetFieldDefs()
{
return _fieldDefs.Rows;
}
protected override bool TryGetMethodDefinitionHandle(IMethodDefinition def, out MethodDefinitionHandle handle)
{
int index;
bool result = _methodDefs.TryGetValue(def, out index);
handle = MetadataTokens.MethodDefinitionHandle(index);
return result;
}
protected override MethodDefinitionHandle GetMethodDefinitionHandle(IMethodDefinition def)
{
return MetadataTokens.MethodDefinitionHandle(_methodDefs[def]);
}
protected override IMethodDefinition GetMethodDef(MethodDefinitionHandle handle)
{
return _methodDefs[MetadataTokens.GetRowNumber(handle)];
}
protected override IReadOnlyList<IMethodDefinition> GetMethodDefs()
{
return _methodDefs.Rows;
}
protected override PropertyDefinitionHandle GetPropertyDefIndex(IPropertyDefinition def)
{
return MetadataTokens.PropertyDefinitionHandle(_propertyDefs[def]);
}
protected override IReadOnlyList<IPropertyDefinition> GetPropertyDefs()
{
return _propertyDefs.Rows;
}
protected override ParameterHandle GetParameterHandle(IParameterDefinition def)
{
return MetadataTokens.ParameterHandle(_parameterDefs[def]);
}
protected override IReadOnlyList<IParameterDefinition> GetParameterDefs()
{
return _parameterDefs.Rows;
}
protected override IReadOnlyList<IGenericParameter> GetGenericParameters()
{
return _genericParameters.Rows;
}
protected override FieldDefinitionHandle GetFirstFieldDefinitionHandle(INamedTypeDefinition typeDef)
{
return MetadataTokens.FieldDefinitionHandle(_fieldDefIndex[typeDef]);
}
protected override MethodDefinitionHandle GetFirstMethodDefinitionHandle(INamedTypeDefinition typeDef)
{
return MetadataTokens.MethodDefinitionHandle(_methodDefIndex[typeDef]);
}
protected override ParameterHandle GetFirstParameterHandle(IMethodDefinition methodDef)
{
return MetadataTokens.ParameterHandle(_parameterListIndex[methodDef]);
}
protected override AssemblyReferenceHandle GetOrAddAssemblyReferenceHandle(IAssemblyReference reference)
{
return MetadataTokens.AssemblyReferenceHandle(_assemblyRefIndex.GetOrAdd(reference.Identity));
}
protected override IReadOnlyList<AssemblyIdentity> GetAssemblyRefs()
{
return _assemblyRefIndex.Rows;
}
protected override ModuleReferenceHandle GetOrAddModuleReferenceHandle(string reference)
{
return MetadataTokens.ModuleReferenceHandle(_moduleRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<string> GetModuleRefs()
{
return _moduleRefIndex.Rows;
}
protected override MemberReferenceHandle GetOrAddMemberReferenceHandle(ITypeMemberReference reference)
{
return MetadataTokens.MemberReferenceHandle(_memberRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeMemberReference> GetMemberRefs()
{
return _memberRefIndex.Rows;
}
protected override MethodSpecificationHandle GetOrAddMethodSpecificationHandle(IGenericMethodInstanceReference reference)
{
return MetadataTokens.MethodSpecificationHandle(_methodSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<IGenericMethodInstanceReference> GetMethodSpecs()
{
return _methodSpecIndex.Rows;
}
protected override int GreatestMethodDefIndex => _methodDefs.NextRowId;
protected override bool TryGetTypeReferenceHandle(ITypeReference reference, out TypeReferenceHandle handle)
{
int index;
bool result = _typeRefIndex.TryGetValue(reference, out index);
handle = MetadataTokens.TypeReferenceHandle(index);
return result;
}
protected override TypeReferenceHandle GetOrAddTypeReferenceHandle(ITypeReference reference)
{
return MetadataTokens.TypeReferenceHandle(_typeRefIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeRefs()
{
return _typeRefIndex.Rows;
}
protected override TypeSpecificationHandle GetOrAddTypeSpecificationHandle(ITypeReference reference)
{
return MetadataTokens.TypeSpecificationHandle(_typeSpecIndex.GetOrAdd(reference));
}
protected override IReadOnlyList<ITypeReference> GetTypeSpecs()
{
return _typeSpecIndex.Rows;
}
protected override StandaloneSignatureHandle GetOrAddStandaloneSignatureHandle(BlobHandle blobIndex)
{
return MetadataTokens.StandaloneSignatureHandle(_standAloneSignatureIndex.GetOrAdd(blobIndex));
}
protected override IReadOnlyList<BlobHandle> GetStandaloneSignatureBlobHandles()
{
return _standAloneSignatureIndex.Rows;
}
protected override ReferenceIndexer CreateReferenceVisitor()
{
return new FullReferenceIndexer(this);
}
protected override void ReportReferencesToAddedSymbols()
{
// noop
}
private sealed class FullReferenceIndexer : ReferenceIndexer
{
internal FullReferenceIndexer(MetadataWriter metadataWriter)
: base(metadataWriter)
{
}
}
protected override void PopulateEventMapTableRows()
{
ITypeDefinition? lastParent = null;
foreach (IEventDefinition eventDef in this.GetEventDefs())
{
if (eventDef.ContainingTypeDefinition == lastParent)
{
continue;
}
lastParent = eventDef.ContainingTypeDefinition;
metadata.AddEventMap(
declaringType: GetTypeDefinitionHandle(lastParent),
eventList: GetEventDefinitionHandle(eventDef));
}
}
protected override void PopulatePropertyMapTableRows()
{
ITypeDefinition? lastParent = null;
foreach (IPropertyDefinition propertyDef in this.GetPropertyDefs())
{
if (propertyDef.ContainingTypeDefinition == lastParent)
{
continue;
}
lastParent = propertyDef.ContainingTypeDefinition;
metadata.AddPropertyMap(
declaringType: GetTypeDefinitionHandle(lastParent),
propertyList: GetPropertyDefIndex(propertyDef));
}
}
protected override void CreateIndicesForNonTypeMembers(ITypeDefinition typeDef)
{
_typeDefs.Add(typeDef);
IEnumerable<IGenericTypeParameter> typeParameters = this.GetConsolidatedTypeParameters(typeDef);
if (typeParameters != null)
{
foreach (IGenericTypeParameter genericParameter in typeParameters)
{
_genericParameters.Add(genericParameter);
}
}
foreach (MethodImplementation methodImplementation in typeDef.GetExplicitImplementationOverrides(Context))
{
this.methodImplList.Add(methodImplementation);
}
foreach (IEventDefinition eventDef in typeDef.GetEvents(Context))
{
_eventDefs.Add(eventDef);
}
_fieldDefIndex.Add(typeDef, _fieldDefs.NextRowId);
foreach (IFieldDefinition fieldDef in typeDef.GetFields(Context))
{
_fieldDefs.Add(fieldDef);
}
_methodDefIndex.Add(typeDef, _methodDefs.NextRowId);
foreach (IMethodDefinition methodDef in typeDef.GetMethods(Context))
{
this.CreateIndicesFor(methodDef);
_methodDefs.Add(methodDef);
}
foreach (IPropertyDefinition propertyDef in typeDef.GetProperties(Context))
{
_propertyDefs.Add(propertyDef);
}
}
private void CreateIndicesFor(IMethodDefinition methodDef)
{
_parameterListIndex.Add(methodDef, _parameterDefs.NextRowId);
foreach (var paramDef in this.GetParametersToEmit(methodDef))
{
_parameterDefs.Add(paramDef);
}
if (methodDef.GenericParameterCount > 0)
{
foreach (IGenericMethodParameter genericParameter in methodDef.GenericParameters)
{
_genericParameters.Add(genericParameter);
}
}
}
private struct DefinitionIndex<T> where T : class, IReference
{
// IReference to RowId
private readonly Dictionary<T, int> _index;
private readonly List<T> _rows;
public DefinitionIndex(int capacity)
{
_index = new Dictionary<T, int>(capacity, ReferenceEqualityComparer.Instance);
_rows = new List<T>(capacity);
}
public bool TryGetValue(T item, out int rowId)
{
return _index.TryGetValue(item, out rowId);
}
public int this[T item]
{
get { return _index[item]; }
}
public T this[int rowId]
{
get { return _rows[rowId - 1]; }
}
public IReadOnlyList<T> Rows
{
get { return _rows; }
}
public int NextRowId
{
get { return _rows.Count + 1; }
}
public void Add(T item)
{
_index.Add(item, NextRowId);
_rows.Add(item);
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/VisualBasic/Portable/Symbols/MergedNamespaceSymbol.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.Collections.ObjectModel
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A MergedNamespaceSymbol represents a namespace that merges the contents of two or more other
''' namespaces. Any sub-namespaces with the same names are also merged if they have two or more
''' instances.
'''
''' Merged namespaces are used to merged the symbols from multiple metadata modules and the source "module"
''' into a single symbol tree that represents all the available symbols. The compiler resolves names
''' against Me merged set of symbols.
'''
''' Typically there will not be very many merged namespaces in a Compilation: only the root namespaces and
''' namespaces that are used in multiple referenced modules. (Microsoft, System, System.Xml,
''' System.Diagnostics, System.Threading, ...)
''' </summary>
Friend MustInherit Class MergedNamespaceSymbol
Inherits PEOrSourceOrMergedNamespaceSymbol
Protected ReadOnly _namespacesToMerge As ImmutableArray(Of NamespaceSymbol)
Protected ReadOnly _containingNamespace As MergedNamespaceSymbol
' The cachedLookup caches results of lookups on the constituent namespaces so
' that subsequent lookups for the same name are much faster than having to ask
' each of the constituent namespaces.
Private ReadOnly _cachedLookup As CachingDictionary(Of String, Symbol)
' This caches results of GetModuleMembers()
Private _lazyModuleMembers As ImmutableArray(Of NamedTypeSymbol)
' This caches results of GetMembers()
Private _lazyMembers As ImmutableArray(Of Symbol)
Private _lazyEmbeddedKind As Integer = EmbeddedSymbolKind.Unset
''' <summary>
''' Create a possibly merged namespace symbol representing global namespace on an assembly level.
''' </summary>
Public Shared Function CreateGlobalNamespace(extent As AssemblySymbol) As NamespaceSymbol
' Get the root namespace from each module, and merge them all together. If there is only one,
' then MergedNamespaceSymbol.Create will just return that one.
Return MergedNamespaceSymbol.Create(extent, Nothing, ConstituentGlobalNamespaces(extent).AsImmutable())
End Function
Private Shared Iterator Function ConstituentGlobalNamespaces(extent As AssemblySymbol) As IEnumerable(Of NamespaceSymbol)
For Each m In extent.Modules
Yield m.GlobalNamespace
Next
End Function
''' <summary>
''' Create a possibly merged namespace symbol. If only a single namespace is passed it, it is just returned directly.
''' If two or more namespaces are passed in, then a new merged namespace is created with the given extent and container.
''' </summary>
''' <param name="extent">The namespace extent to use, IF a merged namespace is created.</param>
''' <param name="containingNamespace">The containing namespace to used, IF a merged namespace is created.</param>
''' <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it is returned.
''' The merged namespace symbol may hold onto the array.</param>
''' <returns></returns>A namespace symbol representing the merged namespace.(of /returns)
Private Shared Function Create(extent As AssemblySymbol, containingNamespace As AssemblyMergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on. However, it means that
' the child namespace of a Compilation extent namespace may be a Module extent namespace, and the containing of that
' module extent namespace will be another module extent namespace. This is basically no different than type members of namespaces,
' so it shouldn't be TOO unexpected.
Debug.Assert(namespacesToMerge.Length <> 0)
If namespacesToMerge.Length = 1 Then
Dim result = namespacesToMerge(0)
Return result
Else
Return New AssemblyMergedNamespaceSymbol(extent, containingNamespace, namespacesToMerge)
End If
End Function
Friend Shared Function CreateForTestPurposes(extent As AssemblySymbol, namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Return Create(extent, Nothing, namespacesToMerge.AsImmutable())
End Function
''' <summary>
''' Create a possibly merged namespace symbol representing global namespace on a compilation level.
''' </summary>
Public Shared Function CreateGlobalNamespace(extent As VisualBasicCompilation) As NamespaceSymbol
' Get the root namespace from each module, and merge them all together.
Return MergedNamespaceSymbol.Create(extent, Nothing, ConstituentGlobalNamespaces(extent))
End Function
Private Shared Iterator Function ConstituentGlobalNamespaces(extent As VisualBasicCompilation) As IEnumerable(Of NamespaceSymbol)
For Each m In extent.Assembly.Modules
Yield m.GlobalNamespace
Next
For Each reference In extent.SourceModule.GetReferencedAssemblySymbols()
For Each m In reference.Modules
Yield m.GlobalNamespace
Next
Next
End Function
Private Shared Function Create(extent As VisualBasicCompilation, containingNamespace As CompilationMergedNamespaceSymbol, namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Dim namespaceArray = ArrayBuilder(Of NamespaceSymbol).GetInstance()
namespaceArray.AddRange(namespacesToMerge)
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on. However, it means that
' the child namespace of a Compilation extent namespace may be a Module extent namespace, and the containing of that
' module extent namespace will be another module extent namespace. This is basically no different than type members of namespaces,
' so it shouldn't be TOO unexpected.
Debug.Assert(namespaceArray.Count <> 0)
If (namespaceArray.Count = 1) Then
Dim result = namespaceArray(0)
namespaceArray.Free()
Return result
Else
Return New CompilationMergedNamespaceSymbol(extent, containingNamespace, namespaceArray.ToImmutableAndFree())
End If
End Function
''' <summary>
''' Create a possibly merged namespace symbol (namespace group). If only a single namespace is passed it, it is just returned directly.
''' If two or more namespaces are passed in, then a new merged namespace is created
''' </summary>
''' <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it is returned.
''' The merged namespace symbol may hold onto the array.</param>
''' <returns></returns>A namespace symbol representing the merged namespace.(of /returns)
Public Shared Function CreateNamespaceGroup(namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Return Create(NamespaceGroupSymbol.GlobalNamespace, namespacesToMerge)
End Function
Public Overridable Function Shrink(namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Throw ExceptionUtilities.Unreachable
End Function
''' <summary>
''' Create a possibly merged namespace symbol (namespace group). If only a single namespace is passed it, it is just returned directly.
''' If two or more namespaces are passed in, then a new merged namespace is created with the given extent and container.
''' </summary>
''' <param name="containingNamespace">The containing namespace to used, IF a merged namespace is created.</param>
''' <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it is returned.
''' The merged namespace symbol may hold onto the array.</param>
''' <returns></returns>A namespace symbol representing the merged namespace.(of /returns)
Private Shared Function Create(containingNamespace As NamespaceGroupSymbol, namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Dim namespaceArray = ArrayBuilder(Of NamespaceSymbol).GetInstance()
namespaceArray.AddRange(namespacesToMerge)
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on. However, it means that
' the child namespace of a Compilation extent namespace may be a Module extent namespace, and the containing of that
' module extent namespace will be another module extent namespace. This is basically no different than type members of namespaces,
' so it shouldn't be TOO unexpected.
Debug.Assert(namespaceArray.Count <> 0)
If (namespaceArray.Count = 1) Then
Dim result = namespaceArray(0)
namespaceArray.Free()
Return result
Else
Return New NamespaceGroupSymbol(containingNamespace, namespaceArray.ToImmutableAndFree())
End If
End Function
' Constructor. Use static Create method to create instances.
Private Sub New(containingNamespace As MergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
Debug.Assert(namespacesToMerge.Distinct().Length = namespacesToMerge.Length)
Me._namespacesToMerge = namespacesToMerge
Me._containingNamespace = containingNamespace
Me._cachedLookup = New CachingDictionary(Of String, Symbol)(AddressOf SlowGetChildrenOfName, AddressOf SlowGetChildNames, IdentifierComparison.Comparer)
End Sub
Friend Function GetConstituentForCompilation(compilation As VisualBasicCompilation) As NamespaceSymbol
For Each constituent In _namespacesToMerge
If constituent.IsFromCompilation(compilation) Then
Return constituent
End If
Next
Return Nothing
End Function
Public Overrides ReadOnly Property ConstituentNamespaces As ImmutableArray(Of NamespaceSymbol)
Get
Return _namespacesToMerge
End Get
End Property
''' <summary>
''' Method that is called from the CachingLookup to lookup the children of a given name. Looks
''' in all the constituent namespaces.
''' </summary>
Private Function SlowGetChildrenOfName(name As String) As ImmutableArray(Of Symbol)
Dim nsSymbols As ArrayBuilder(Of NamespaceSymbol) = Nothing
Dim otherSymbols = ArrayBuilder(Of Symbol).GetInstance()
' Accumulate all the child namespaces and types.
For Each nsSym As NamespaceSymbol In _namespacesToMerge
For Each childSym As Symbol In nsSym.GetMembers(name)
If (childSym.Kind = SymbolKind.Namespace) Then
nsSymbols = If(nsSymbols, ArrayBuilder(Of NamespaceSymbol).GetInstance())
nsSymbols.Add(DirectCast(childSym, NamespaceSymbol))
Else
otherSymbols.Add(childSym)
End If
Next
Next
If nsSymbols IsNot Nothing Then
otherSymbols.Add(CreateChildMergedNamespaceSymbol(nsSymbols.ToImmutableAndFree()))
End If
Return otherSymbols.ToImmutableAndFree()
End Function
Protected MustOverride Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
''' <summary>
''' Method that is called from the CachingLookup to get all child names. Looks
''' in all constituent namespaces.
''' </summary>
Private Function SlowGetChildNames(comparer As IEqualityComparer(Of String)) As HashSet(Of String)
Dim childNames As New HashSet(Of String)(comparer)
For Each nsSym As NamespaceSymbol In _namespacesToMerge
For Each childSym As NamespaceOrTypeSymbol In nsSym.GetMembersUnordered()
childNames.Add(childSym.Name)
Next
Next
Return childNames
End Function
Public Overrides ReadOnly Property Name As String
Get
Return _namespacesToMerge(0).Name
End Get
End Property
Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
If _lazyEmbeddedKind = EmbeddedSymbolKind.Unset Then
Dim value As Integer = EmbeddedSymbolKind.None
For Each ns In _namespacesToMerge
value = value Or ns.EmbeddedSymbolKind
Next
Interlocked.CompareExchange(_lazyEmbeddedKind, value, EmbeddedSymbolKind.Unset)
End If
Return CType(_lazyEmbeddedKind, EmbeddedSymbolKind)
End Get
End Property
' This is very performance critical for type lookup.
' It's important that this NOT enumerable and instantiate all the members. Instead, we just want to return
' all the modules in all constituent namespaces, and cache that.
Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol)
If _lazyModuleMembers.IsDefault Then
Dim moduleMembers = ArrayBuilder(Of NamedTypeSymbol).GetInstance()
' Accumulate all the child modules.
For Each nsSym As NamespaceSymbol In _namespacesToMerge
moduleMembers.AddRange(nsSym.GetModuleMembers())
Next
ImmutableInterlocked.InterlockedCompareExchange(_lazyModuleMembers,
moduleMembers.ToImmutableAndFree,
Nothing)
End If
Return _lazyModuleMembers
End Function
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
If _lazyMembers.IsDefault Then
Dim builder = ArrayBuilder(Of Symbol).GetInstance()
_cachedLookup.AddValues(builder)
_lazyMembers = builder.ToImmutableAndFree()
End If
Return _lazyMembers
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return _cachedLookup(name)
End Function
Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray.CreateRange(Of NamedTypeSymbol)(GetMembersUnordered().OfType(Of NamedTypeSymbol))
End Function
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray.CreateRange(Of NamedTypeSymbol)(GetMembers().OfType(Of NamedTypeSymbol))
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
'TODO - Perf
Return ImmutableArray.CreateRange(Of NamedTypeSymbol)(GetMembers(name).OfType(Of NamedTypeSymbol))
End Function
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _containingNamespace
End Get
End Property
Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol
Get
If Me.Extent.Kind = NamespaceKind.Module Then
Return Me.Extent.Module.ContainingAssembly
ElseIf Me.Extent.Kind = NamespaceKind.Assembly Then
Return Me.Extent.Assembly
Else
Return Nothing
End If
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.CreateRange(Of Location)((From ns In _namespacesToMerge, loc In ns.Locations Select loc))
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray.CreateRange(Of SyntaxReference)(From ns In _namespacesToMerge, reference In ns.DeclaringSyntaxReferences Select reference)
End Get
End Property
''' <summary>
''' Calculate declared accessibility of most accessible type within this namespace or within a containing namespace recursively.
''' Expected to be called at most once per namespace symbol, unless there is a race condition.
'''
''' Valid return values:
''' Friend,
''' Public,
''' NotApplicable - if there are no types.
''' </summary>
Protected NotOverridable Overrides Function GetDeclaredAccessibilityOfMostAccessibleDescendantType() As Accessibility
Dim result As Accessibility = Accessibility.NotApplicable
For Each nsSym As NamespaceSymbol In _namespacesToMerge
Dim current As Accessibility = nsSym.DeclaredAccessibilityOfMostAccessibleDescendantType
If current > result Then
If current = Accessibility.Public Then
Return Accessibility.Public
End If
result = current
End If
Next
Return result
End Function
Friend Overrides Function IsDeclaredInSourceModule([module] As ModuleSymbol) As Boolean
For Each nsSym As NamespaceSymbol In _namespacesToMerge
If nsSym.IsDeclaredInSourceModule([module]) Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' For test purposes only.
''' </summary>
Friend MustOverride ReadOnly Property RawContainsAccessibleTypes As ThreeState
Private NotInheritable Class AssemblyMergedNamespaceSymbol
Inherits MergedNamespaceSymbol
Private ReadOnly _assembly As AssemblySymbol
Public Sub New(assembly As AssemblySymbol, containingNamespace As AssemblyMergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
MyBase.New(containingNamespace, namespacesToMerge)
#If DEBUG Then
' We shouldn't merge merged namespaces.
For Each ns In namespacesToMerge
Debug.Assert(ns.ConstituentNamespaces.Length = 1)
Next
#End If
Debug.Assert(namespacesToMerge.Length > 0)
Debug.Assert(containingNamespace Is Nothing OrElse containingNamespace._assembly Is assembly)
Me._assembly = assembly
End Sub
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
Return New NamespaceExtent(_assembly)
End Get
End Property
Protected Overrides Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
Return MergedNamespaceSymbol.Create(_assembly, Me, nsSymbols)
End Function
Friend Overrides ReadOnly Property RawContainsAccessibleTypes As ThreeState
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Sub BuildExtensionMethodsMap(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))
' Assembly merged namespace symbols aren't used by binders.
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
' Assembly merged namespace symbols aren't used by binders.
Throw ExceptionUtilities.Unreachable
End Get
End Property
End Class
Private NotInheritable Class CompilationMergedNamespaceSymbol
Inherits MergedNamespaceSymbol
Private ReadOnly _compilation As VisualBasicCompilation
Private _containsAccessibleTypes As ThreeState = ThreeState.Unknown
Private _isDeclaredInSourceModule As ThreeState = ThreeState.Unknown
Friend Overrides ReadOnly Property RawContainsAccessibleTypes As ThreeState
Get
Return _containsAccessibleTypes
End Get
End Property
Public Sub New(compilation As VisualBasicCompilation, containingNamespace As CompilationMergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
MyBase.New(containingNamespace, namespacesToMerge)
#If DEBUG Then
' We shouldn't merge merged namespaces.
For Each ns In namespacesToMerge
Debug.Assert(ns.ConstituentNamespaces.Length = 1)
Next
#End If
Debug.Assert(namespacesToMerge.Length > 0)
Debug.Assert(containingNamespace Is Nothing OrElse containingNamespace._compilation Is compilation)
Me._compilation = compilation
End Sub
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
Return New NamespaceExtent(_compilation)
End Get
End Property
Protected Overrides Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
Return MergedNamespaceSymbol.Create(_compilation, Me, nsSymbols)
End Function
''' <summary>
''' Returns true if namespace contains types accessible from the target assembly.
''' </summary>
Friend Overrides Function ContainsTypesAccessibleFrom(fromAssembly As AssemblySymbol) As Boolean
' For a compilation merged namespace we only need to support scenario when
' [fromAssembly] is compilation's assembly, because this namespace symbol will never be
' "imported" namespace in context of other compilation.
' This allows us to do efficient caching of the result.
Debug.Assert(fromAssembly Is _compilation.Assembly)
If _containsAccessibleTypes.HasValue Then
Return _containsAccessibleTypes = ThreeState.True
End If
If Me.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType = Accessibility.Public Then
Return True
End If
Dim result As Boolean = False
For Each nsSym As NamespaceSymbol In _namespacesToMerge
If nsSym.ContainsTypesAccessibleFrom(fromAssembly) Then
result = True
Exit For
End If
Next
If result Then
_containsAccessibleTypes = ThreeState.True
' Bubble up the value.
Dim parent = TryCast(Me.ContainingSymbol, CompilationMergedNamespaceSymbol)
While parent IsNot Nothing AndAlso
parent._containsAccessibleTypes = ThreeState.Unknown
parent._containsAccessibleTypes = ThreeState.True
parent = TryCast(parent.ContainingSymbol, CompilationMergedNamespaceSymbol)
End While
Else
_containsAccessibleTypes = ThreeState.False
End If
Return result
End Function
Friend Overrides Function IsDeclaredInSourceModule([module] As ModuleSymbol) As Boolean
' For a compilation merged namespace we only need to support scenario when
' [module] is compilation's source module, because this namespace symbol will never be
' "imported" namespace in context of other compilation.
' This allows us to do efficient caching of the result.
Debug.Assert([module] Is _compilation.SourceModule)
If _isDeclaredInSourceModule.HasValue Then
Return _isDeclaredInSourceModule = ThreeState.True
End If
Dim result = MyBase.IsDeclaredInSourceModule([module])
If result Then
_isDeclaredInSourceModule = ThreeState.True
' Bubble up the value.
Dim parent = TryCast(Me.ContainingSymbol, CompilationMergedNamespaceSymbol)
While parent IsNot Nothing AndAlso
parent._isDeclaredInSourceModule = ThreeState.Unknown
parent._isDeclaredInSourceModule = ThreeState.True
parent = TryCast(parent.ContainingSymbol, CompilationMergedNamespaceSymbol)
End While
Else
_isDeclaredInSourceModule = ThreeState.False
End If
Return result
End Function
''' <summary>
''' Populate the map with all extension methods declared within this namespace, so that methods from
''' the same type are grouped together within each bucket.
''' </summary>
Friend Overrides Sub BuildExtensionMethodsMap(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))
For Each nsSym As NamespaceSymbol In _namespacesToMerge
' CONSIDER: Is it worth using m_lazyExtensionMethodsMap for nsSym if we've built it already for a
' different compilation?
nsSym.BuildExtensionMethodsMap(map)
Next
End Sub
Friend Overrides Sub GetExtensionMethods(methods As ArrayBuilder(Of MethodSymbol), name As String)
For Each nsSym As NamespaceSymbol In _namespacesToMerge
nsSym.GetExtensionMethods(methods, name)
Next
End Sub
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
' We should override all callers of this function and go through implementation
' provided by each individual namespace symbol.
Throw ExceptionUtilities.Unreachable
End Get
End Property
End Class
Private NotInheritable Class NamespaceGroupSymbol
Inherits MergedNamespaceSymbol
Public Shared ReadOnly GlobalNamespace As New NamespaceGroupSymbol(Nothing, ImmutableArray(Of NamespaceSymbol).Empty)
Public Sub New(containingNamespace As NamespaceGroupSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
MyBase.New(containingNamespace, namespacesToMerge)
#If DEBUG Then
Dim name As String = If(namespacesToMerge.Length > 0, namespacesToMerge(0).Name, Nothing)
For Each ns In namespacesToMerge
Debug.Assert(ns.NamespaceKind = NamespaceKind.Module OrElse ns.NamespaceKind = NamespaceKind.Compilation)
Debug.Assert(Not ns.IsGlobalNamespace)
Debug.Assert(IdentifierComparison.Equals(name, ns.Name))
Next
#End If
Debug.Assert(containingNamespace Is Nothing OrElse namespacesToMerge.Length > 0)
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return If(_namespacesToMerge.Length > 0, _namespacesToMerge(0).Name, "")
End Get
End Property
#If DEBUG Then
Shared Sub New()
' Below is a set of compile time asserts, they break build if violated.
' Assert(SymbolExtensions.NamespaceKindNamespaceGroup = 0)
' This is needed because we use default NamespaceExtent constructor in Extent property.
Const assert01_1 As Integer = SymbolExtensions.NamespaceKindNamespaceGroup + Int32.MaxValue
Const assert01_2 As Integer = SymbolExtensions.NamespaceKindNamespaceGroup + Int32.MinValue
Dim dummy = assert01_1 + assert01_2
End Sub
#End If
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
Return New NamespaceExtent()
End Get
End Property
Friend Overrides ReadOnly Property RawContainsAccessibleTypes As ThreeState
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Sub BuildExtensionMethodsMap(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))
Throw ExceptionUtilities.Unreachable
End Sub
Protected Overrides Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
Return MergedNamespaceSymbol.Create(Me, nsSymbols)
End Function
Public Overrides Function Shrink(namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Dim namespaceArray = ArrayBuilder(Of NamespaceSymbol).GetInstance()
namespaceArray.AddRange(namespacesToMerge)
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on.
Debug.Assert(namespaceArray.Count <> 0)
If namespaceArray.Count = 0 Then
namespaceArray.Free()
Return Me
End If
' New set of parts should be a subset of what we already have
If namespaceArray.Count = 1 Then
Dim result = namespaceArray(0)
namespaceArray.Free()
If _namespacesToMerge.Contains(result) Then
Return result
End If
Throw ExceptionUtilities.Unreachable
End If
Dim lookup = New SmallDictionary(Of NamespaceSymbol, Boolean)()
For Each item In _namespacesToMerge
lookup(item) = False
Next
For Each item In namespaceArray
If Not lookup.TryGetValue(item, Nothing) Then
Debug.Assert(False)
namespaceArray.Free()
Return Me
End If
Next
Return Shrink(namespaceArray.ToImmutableAndFree())
End Function
Private Overloads Function Shrink(namespaceArray As ImmutableArray(Of NamespaceSymbol)) As NamespaceGroupSymbol
Debug.Assert(namespaceArray.Length < _namespacesToMerge.Length)
If namespaceArray.Length >= _namespacesToMerge.Length Then
Debug.Assert(False)
Return Me
End If
If _containingNamespace Is GlobalNamespace Then
Return New NamespaceGroupSymbol(GlobalNamespace, namespaceArray)
End If
Dim parentsArray = ArrayBuilder(Of NamespaceSymbol).GetInstance(namespaceArray.Length)
For Each item In namespaceArray
parentsArray.Add(item.ContainingNamespace)
Next
Return New NamespaceGroupSymbol(DirectCast(_containingNamespace, NamespaceGroupSymbol).Shrink(parentsArray.ToImmutableAndFree()), namespaceArray)
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Generic
Imports System.Collections.Immutable
Imports System.Collections.ObjectModel
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols
''' <summary>
''' A MergedNamespaceSymbol represents a namespace that merges the contents of two or more other
''' namespaces. Any sub-namespaces with the same names are also merged if they have two or more
''' instances.
'''
''' Merged namespaces are used to merged the symbols from multiple metadata modules and the source "module"
''' into a single symbol tree that represents all the available symbols. The compiler resolves names
''' against Me merged set of symbols.
'''
''' Typically there will not be very many merged namespaces in a Compilation: only the root namespaces and
''' namespaces that are used in multiple referenced modules. (Microsoft, System, System.Xml,
''' System.Diagnostics, System.Threading, ...)
''' </summary>
Friend MustInherit Class MergedNamespaceSymbol
Inherits PEOrSourceOrMergedNamespaceSymbol
Protected ReadOnly _namespacesToMerge As ImmutableArray(Of NamespaceSymbol)
Protected ReadOnly _containingNamespace As MergedNamespaceSymbol
' The cachedLookup caches results of lookups on the constituent namespaces so
' that subsequent lookups for the same name are much faster than having to ask
' each of the constituent namespaces.
Private ReadOnly _cachedLookup As CachingDictionary(Of String, Symbol)
' This caches results of GetModuleMembers()
Private _lazyModuleMembers As ImmutableArray(Of NamedTypeSymbol)
' This caches results of GetMembers()
Private _lazyMembers As ImmutableArray(Of Symbol)
Private _lazyEmbeddedKind As Integer = EmbeddedSymbolKind.Unset
''' <summary>
''' Create a possibly merged namespace symbol representing global namespace on an assembly level.
''' </summary>
Public Shared Function CreateGlobalNamespace(extent As AssemblySymbol) As NamespaceSymbol
' Get the root namespace from each module, and merge them all together. If there is only one,
' then MergedNamespaceSymbol.Create will just return that one.
Return MergedNamespaceSymbol.Create(extent, Nothing, ConstituentGlobalNamespaces(extent).AsImmutable())
End Function
Private Shared Iterator Function ConstituentGlobalNamespaces(extent As AssemblySymbol) As IEnumerable(Of NamespaceSymbol)
For Each m In extent.Modules
Yield m.GlobalNamespace
Next
End Function
''' <summary>
''' Create a possibly merged namespace symbol. If only a single namespace is passed it, it is just returned directly.
''' If two or more namespaces are passed in, then a new merged namespace is created with the given extent and container.
''' </summary>
''' <param name="extent">The namespace extent to use, IF a merged namespace is created.</param>
''' <param name="containingNamespace">The containing namespace to used, IF a merged namespace is created.</param>
''' <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it is returned.
''' The merged namespace symbol may hold onto the array.</param>
''' <returns></returns>A namespace symbol representing the merged namespace.(of /returns)
Private Shared Function Create(extent As AssemblySymbol, containingNamespace As AssemblyMergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on. However, it means that
' the child namespace of a Compilation extent namespace may be a Module extent namespace, and the containing of that
' module extent namespace will be another module extent namespace. This is basically no different than type members of namespaces,
' so it shouldn't be TOO unexpected.
Debug.Assert(namespacesToMerge.Length <> 0)
If namespacesToMerge.Length = 1 Then
Dim result = namespacesToMerge(0)
Return result
Else
Return New AssemblyMergedNamespaceSymbol(extent, containingNamespace, namespacesToMerge)
End If
End Function
Friend Shared Function CreateForTestPurposes(extent As AssemblySymbol, namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Return Create(extent, Nothing, namespacesToMerge.AsImmutable())
End Function
''' <summary>
''' Create a possibly merged namespace symbol representing global namespace on a compilation level.
''' </summary>
Public Shared Function CreateGlobalNamespace(extent As VisualBasicCompilation) As NamespaceSymbol
' Get the root namespace from each module, and merge them all together.
Return MergedNamespaceSymbol.Create(extent, Nothing, ConstituentGlobalNamespaces(extent))
End Function
Private Shared Iterator Function ConstituentGlobalNamespaces(extent As VisualBasicCompilation) As IEnumerable(Of NamespaceSymbol)
For Each m In extent.Assembly.Modules
Yield m.GlobalNamespace
Next
For Each reference In extent.SourceModule.GetReferencedAssemblySymbols()
For Each m In reference.Modules
Yield m.GlobalNamespace
Next
Next
End Function
Private Shared Function Create(extent As VisualBasicCompilation, containingNamespace As CompilationMergedNamespaceSymbol, namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Dim namespaceArray = ArrayBuilder(Of NamespaceSymbol).GetInstance()
namespaceArray.AddRange(namespacesToMerge)
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on. However, it means that
' the child namespace of a Compilation extent namespace may be a Module extent namespace, and the containing of that
' module extent namespace will be another module extent namespace. This is basically no different than type members of namespaces,
' so it shouldn't be TOO unexpected.
Debug.Assert(namespaceArray.Count <> 0)
If (namespaceArray.Count = 1) Then
Dim result = namespaceArray(0)
namespaceArray.Free()
Return result
Else
Return New CompilationMergedNamespaceSymbol(extent, containingNamespace, namespaceArray.ToImmutableAndFree())
End If
End Function
''' <summary>
''' Create a possibly merged namespace symbol (namespace group). If only a single namespace is passed it, it is just returned directly.
''' If two or more namespaces are passed in, then a new merged namespace is created
''' </summary>
''' <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it is returned.
''' The merged namespace symbol may hold onto the array.</param>
''' <returns></returns>A namespace symbol representing the merged namespace.(of /returns)
Public Shared Function CreateNamespaceGroup(namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Return Create(NamespaceGroupSymbol.GlobalNamespace, namespacesToMerge)
End Function
Public Overridable Function Shrink(namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Throw ExceptionUtilities.Unreachable
End Function
''' <summary>
''' Create a possibly merged namespace symbol (namespace group). If only a single namespace is passed it, it is just returned directly.
''' If two or more namespaces are passed in, then a new merged namespace is created with the given extent and container.
''' </summary>
''' <param name="containingNamespace">The containing namespace to used, IF a merged namespace is created.</param>
''' <param name="namespacesToMerge">One or more namespaces to merged. If just one, then it is returned.
''' The merged namespace symbol may hold onto the array.</param>
''' <returns></returns>A namespace symbol representing the merged namespace.(of /returns)
Private Shared Function Create(containingNamespace As NamespaceGroupSymbol, namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Dim namespaceArray = ArrayBuilder(Of NamespaceSymbol).GetInstance()
namespaceArray.AddRange(namespacesToMerge)
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on. However, it means that
' the child namespace of a Compilation extent namespace may be a Module extent namespace, and the containing of that
' module extent namespace will be another module extent namespace. This is basically no different than type members of namespaces,
' so it shouldn't be TOO unexpected.
Debug.Assert(namespaceArray.Count <> 0)
If (namespaceArray.Count = 1) Then
Dim result = namespaceArray(0)
namespaceArray.Free()
Return result
Else
Return New NamespaceGroupSymbol(containingNamespace, namespaceArray.ToImmutableAndFree())
End If
End Function
' Constructor. Use static Create method to create instances.
Private Sub New(containingNamespace As MergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
Debug.Assert(namespacesToMerge.Distinct().Length = namespacesToMerge.Length)
Me._namespacesToMerge = namespacesToMerge
Me._containingNamespace = containingNamespace
Me._cachedLookup = New CachingDictionary(Of String, Symbol)(AddressOf SlowGetChildrenOfName, AddressOf SlowGetChildNames, IdentifierComparison.Comparer)
End Sub
Friend Function GetConstituentForCompilation(compilation As VisualBasicCompilation) As NamespaceSymbol
For Each constituent In _namespacesToMerge
If constituent.IsFromCompilation(compilation) Then
Return constituent
End If
Next
Return Nothing
End Function
Public Overrides ReadOnly Property ConstituentNamespaces As ImmutableArray(Of NamespaceSymbol)
Get
Return _namespacesToMerge
End Get
End Property
''' <summary>
''' Method that is called from the CachingLookup to lookup the children of a given name. Looks
''' in all the constituent namespaces.
''' </summary>
Private Function SlowGetChildrenOfName(name As String) As ImmutableArray(Of Symbol)
Dim nsSymbols As ArrayBuilder(Of NamespaceSymbol) = Nothing
Dim otherSymbols = ArrayBuilder(Of Symbol).GetInstance()
' Accumulate all the child namespaces and types.
For Each nsSym As NamespaceSymbol In _namespacesToMerge
For Each childSym As Symbol In nsSym.GetMembers(name)
If (childSym.Kind = SymbolKind.Namespace) Then
nsSymbols = If(nsSymbols, ArrayBuilder(Of NamespaceSymbol).GetInstance())
nsSymbols.Add(DirectCast(childSym, NamespaceSymbol))
Else
otherSymbols.Add(childSym)
End If
Next
Next
If nsSymbols IsNot Nothing Then
otherSymbols.Add(CreateChildMergedNamespaceSymbol(nsSymbols.ToImmutableAndFree()))
End If
Return otherSymbols.ToImmutableAndFree()
End Function
Protected MustOverride Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
''' <summary>
''' Method that is called from the CachingLookup to get all child names. Looks
''' in all constituent namespaces.
''' </summary>
Private Function SlowGetChildNames(comparer As IEqualityComparer(Of String)) As HashSet(Of String)
Dim childNames As New HashSet(Of String)(comparer)
For Each nsSym As NamespaceSymbol In _namespacesToMerge
For Each childSym As NamespaceOrTypeSymbol In nsSym.GetMembersUnordered()
childNames.Add(childSym.Name)
Next
Next
Return childNames
End Function
Public Overrides ReadOnly Property Name As String
Get
Return _namespacesToMerge(0).Name
End Get
End Property
Friend Overrides ReadOnly Property EmbeddedSymbolKind As EmbeddedSymbolKind
Get
If _lazyEmbeddedKind = EmbeddedSymbolKind.Unset Then
Dim value As Integer = EmbeddedSymbolKind.None
For Each ns In _namespacesToMerge
value = value Or ns.EmbeddedSymbolKind
Next
Interlocked.CompareExchange(_lazyEmbeddedKind, value, EmbeddedSymbolKind.Unset)
End If
Return CType(_lazyEmbeddedKind, EmbeddedSymbolKind)
End Get
End Property
' This is very performance critical for type lookup.
' It's important that this NOT enumerable and instantiate all the members. Instead, we just want to return
' all the modules in all constituent namespaces, and cache that.
Public Overrides Function GetModuleMembers() As ImmutableArray(Of NamedTypeSymbol)
If _lazyModuleMembers.IsDefault Then
Dim moduleMembers = ArrayBuilder(Of NamedTypeSymbol).GetInstance()
' Accumulate all the child modules.
For Each nsSym As NamespaceSymbol In _namespacesToMerge
moduleMembers.AddRange(nsSym.GetModuleMembers())
Next
ImmutableInterlocked.InterlockedCompareExchange(_lazyModuleMembers,
moduleMembers.ToImmutableAndFree,
Nothing)
End If
Return _lazyModuleMembers
End Function
Public Overrides Function GetMembers() As ImmutableArray(Of Symbol)
If _lazyMembers.IsDefault Then
Dim builder = ArrayBuilder(Of Symbol).GetInstance()
_cachedLookup.AddValues(builder)
_lazyMembers = builder.ToImmutableAndFree()
End If
Return _lazyMembers
End Function
Public Overrides Function GetMembers(name As String) As ImmutableArray(Of Symbol)
Return _cachedLookup(name)
End Function
Friend Overrides Function GetTypeMembersUnordered() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray.CreateRange(Of NamedTypeSymbol)(GetMembersUnordered().OfType(Of NamedTypeSymbol))
End Function
Public Overrides Function GetTypeMembers() As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray.CreateRange(Of NamedTypeSymbol)(GetMembers().OfType(Of NamedTypeSymbol))
End Function
Public Overrides Function GetTypeMembers(name As String) As ImmutableArray(Of NamedTypeSymbol)
'TODO - Perf
Return ImmutableArray.CreateRange(Of NamedTypeSymbol)(GetMembers(name).OfType(Of NamedTypeSymbol))
End Function
Public Overrides ReadOnly Property ContainingSymbol As Symbol
Get
Return _containingNamespace
End Get
End Property
Public Overrides ReadOnly Property ContainingAssembly As AssemblySymbol
Get
If Me.Extent.Kind = NamespaceKind.Module Then
Return Me.Extent.Module.ContainingAssembly
ElseIf Me.Extent.Kind = NamespaceKind.Assembly Then
Return Me.Extent.Assembly
Else
Return Nothing
End If
End Get
End Property
Public Overrides ReadOnly Property Locations As ImmutableArray(Of Location)
Get
Return ImmutableArray.CreateRange(Of Location)((From ns In _namespacesToMerge, loc In ns.Locations Select loc))
End Get
End Property
Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference)
Get
Return ImmutableArray.CreateRange(Of SyntaxReference)(From ns In _namespacesToMerge, reference In ns.DeclaringSyntaxReferences Select reference)
End Get
End Property
''' <summary>
''' Calculate declared accessibility of most accessible type within this namespace or within a containing namespace recursively.
''' Expected to be called at most once per namespace symbol, unless there is a race condition.
'''
''' Valid return values:
''' Friend,
''' Public,
''' NotApplicable - if there are no types.
''' </summary>
Protected NotOverridable Overrides Function GetDeclaredAccessibilityOfMostAccessibleDescendantType() As Accessibility
Dim result As Accessibility = Accessibility.NotApplicable
For Each nsSym As NamespaceSymbol In _namespacesToMerge
Dim current As Accessibility = nsSym.DeclaredAccessibilityOfMostAccessibleDescendantType
If current > result Then
If current = Accessibility.Public Then
Return Accessibility.Public
End If
result = current
End If
Next
Return result
End Function
Friend Overrides Function IsDeclaredInSourceModule([module] As ModuleSymbol) As Boolean
For Each nsSym As NamespaceSymbol In _namespacesToMerge
If nsSym.IsDeclaredInSourceModule([module]) Then
Return True
End If
Next
Return False
End Function
''' <summary>
''' For test purposes only.
''' </summary>
Friend MustOverride ReadOnly Property RawContainsAccessibleTypes As ThreeState
Private NotInheritable Class AssemblyMergedNamespaceSymbol
Inherits MergedNamespaceSymbol
Private ReadOnly _assembly As AssemblySymbol
Public Sub New(assembly As AssemblySymbol, containingNamespace As AssemblyMergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
MyBase.New(containingNamespace, namespacesToMerge)
#If DEBUG Then
' We shouldn't merge merged namespaces.
For Each ns In namespacesToMerge
Debug.Assert(ns.ConstituentNamespaces.Length = 1)
Next
#End If
Debug.Assert(namespacesToMerge.Length > 0)
Debug.Assert(containingNamespace Is Nothing OrElse containingNamespace._assembly Is assembly)
Me._assembly = assembly
End Sub
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
Return New NamespaceExtent(_assembly)
End Get
End Property
Protected Overrides Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
Return MergedNamespaceSymbol.Create(_assembly, Me, nsSymbols)
End Function
Friend Overrides ReadOnly Property RawContainsAccessibleTypes As ThreeState
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Sub BuildExtensionMethodsMap(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))
' Assembly merged namespace symbols aren't used by binders.
Throw ExceptionUtilities.Unreachable
End Sub
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
' Assembly merged namespace symbols aren't used by binders.
Throw ExceptionUtilities.Unreachable
End Get
End Property
End Class
Private NotInheritable Class CompilationMergedNamespaceSymbol
Inherits MergedNamespaceSymbol
Private ReadOnly _compilation As VisualBasicCompilation
Private _containsAccessibleTypes As ThreeState = ThreeState.Unknown
Private _isDeclaredInSourceModule As ThreeState = ThreeState.Unknown
Friend Overrides ReadOnly Property RawContainsAccessibleTypes As ThreeState
Get
Return _containsAccessibleTypes
End Get
End Property
Public Sub New(compilation As VisualBasicCompilation, containingNamespace As CompilationMergedNamespaceSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
MyBase.New(containingNamespace, namespacesToMerge)
#If DEBUG Then
' We shouldn't merge merged namespaces.
For Each ns In namespacesToMerge
Debug.Assert(ns.ConstituentNamespaces.Length = 1)
Next
#End If
Debug.Assert(namespacesToMerge.Length > 0)
Debug.Assert(containingNamespace Is Nothing OrElse containingNamespace._compilation Is compilation)
Me._compilation = compilation
End Sub
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
Return New NamespaceExtent(_compilation)
End Get
End Property
Protected Overrides Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
Return MergedNamespaceSymbol.Create(_compilation, Me, nsSymbols)
End Function
''' <summary>
''' Returns true if namespace contains types accessible from the target assembly.
''' </summary>
Friend Overrides Function ContainsTypesAccessibleFrom(fromAssembly As AssemblySymbol) As Boolean
' For a compilation merged namespace we only need to support scenario when
' [fromAssembly] is compilation's assembly, because this namespace symbol will never be
' "imported" namespace in context of other compilation.
' This allows us to do efficient caching of the result.
Debug.Assert(fromAssembly Is _compilation.Assembly)
If _containsAccessibleTypes.HasValue Then
Return _containsAccessibleTypes = ThreeState.True
End If
If Me.RawLazyDeclaredAccessibilityOfMostAccessibleDescendantType = Accessibility.Public Then
Return True
End If
Dim result As Boolean = False
For Each nsSym As NamespaceSymbol In _namespacesToMerge
If nsSym.ContainsTypesAccessibleFrom(fromAssembly) Then
result = True
Exit For
End If
Next
If result Then
_containsAccessibleTypes = ThreeState.True
' Bubble up the value.
Dim parent = TryCast(Me.ContainingSymbol, CompilationMergedNamespaceSymbol)
While parent IsNot Nothing AndAlso
parent._containsAccessibleTypes = ThreeState.Unknown
parent._containsAccessibleTypes = ThreeState.True
parent = TryCast(parent.ContainingSymbol, CompilationMergedNamespaceSymbol)
End While
Else
_containsAccessibleTypes = ThreeState.False
End If
Return result
End Function
Friend Overrides Function IsDeclaredInSourceModule([module] As ModuleSymbol) As Boolean
' For a compilation merged namespace we only need to support scenario when
' [module] is compilation's source module, because this namespace symbol will never be
' "imported" namespace in context of other compilation.
' This allows us to do efficient caching of the result.
Debug.Assert([module] Is _compilation.SourceModule)
If _isDeclaredInSourceModule.HasValue Then
Return _isDeclaredInSourceModule = ThreeState.True
End If
Dim result = MyBase.IsDeclaredInSourceModule([module])
If result Then
_isDeclaredInSourceModule = ThreeState.True
' Bubble up the value.
Dim parent = TryCast(Me.ContainingSymbol, CompilationMergedNamespaceSymbol)
While parent IsNot Nothing AndAlso
parent._isDeclaredInSourceModule = ThreeState.Unknown
parent._isDeclaredInSourceModule = ThreeState.True
parent = TryCast(parent.ContainingSymbol, CompilationMergedNamespaceSymbol)
End While
Else
_isDeclaredInSourceModule = ThreeState.False
End If
Return result
End Function
''' <summary>
''' Populate the map with all extension methods declared within this namespace, so that methods from
''' the same type are grouped together within each bucket.
''' </summary>
Friend Overrides Sub BuildExtensionMethodsMap(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))
For Each nsSym As NamespaceSymbol In _namespacesToMerge
' CONSIDER: Is it worth using m_lazyExtensionMethodsMap for nsSym if we've built it already for a
' different compilation?
nsSym.BuildExtensionMethodsMap(map)
Next
End Sub
Friend Overrides Sub GetExtensionMethods(methods As ArrayBuilder(Of MethodSymbol), name As String)
For Each nsSym As NamespaceSymbol In _namespacesToMerge
nsSym.GetExtensionMethods(methods, name)
Next
End Sub
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
' We should override all callers of this function and go through implementation
' provided by each individual namespace symbol.
Throw ExceptionUtilities.Unreachable
End Get
End Property
End Class
Private NotInheritable Class NamespaceGroupSymbol
Inherits MergedNamespaceSymbol
Public Shared ReadOnly GlobalNamespace As New NamespaceGroupSymbol(Nothing, ImmutableArray(Of NamespaceSymbol).Empty)
Public Sub New(containingNamespace As NamespaceGroupSymbol, namespacesToMerge As ImmutableArray(Of NamespaceSymbol))
MyBase.New(containingNamespace, namespacesToMerge)
#If DEBUG Then
Dim name As String = If(namespacesToMerge.Length > 0, namespacesToMerge(0).Name, Nothing)
For Each ns In namespacesToMerge
Debug.Assert(ns.NamespaceKind = NamespaceKind.Module OrElse ns.NamespaceKind = NamespaceKind.Compilation)
Debug.Assert(Not ns.IsGlobalNamespace)
Debug.Assert(IdentifierComparison.Equals(name, ns.Name))
Next
#End If
Debug.Assert(containingNamespace Is Nothing OrElse namespacesToMerge.Length > 0)
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return If(_namespacesToMerge.Length > 0, _namespacesToMerge(0).Name, "")
End Get
End Property
#If DEBUG Then
Shared Sub New()
' Below is a set of compile time asserts, they break build if violated.
' Assert(SymbolExtensions.NamespaceKindNamespaceGroup = 0)
' This is needed because we use default NamespaceExtent constructor in Extent property.
Const assert01_1 As Integer = SymbolExtensions.NamespaceKindNamespaceGroup + Int32.MaxValue
Const assert01_2 As Integer = SymbolExtensions.NamespaceKindNamespaceGroup + Int32.MinValue
Dim dummy = assert01_1 + assert01_2
End Sub
#End If
Friend Overrides ReadOnly Property Extent As NamespaceExtent
Get
Return New NamespaceExtent()
End Get
End Property
Friend Overrides ReadOnly Property RawContainsAccessibleTypes As ThreeState
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides ReadOnly Property TypesToCheckForExtensionMethods As ImmutableArray(Of NamedTypeSymbol)
Get
Throw ExceptionUtilities.Unreachable
End Get
End Property
Friend Overrides Sub BuildExtensionMethodsMap(map As Dictionary(Of String, ArrayBuilder(Of MethodSymbol)))
Throw ExceptionUtilities.Unreachable
End Sub
Protected Overrides Function CreateChildMergedNamespaceSymbol(nsSymbols As ImmutableArray(Of NamespaceSymbol)) As NamespaceSymbol
Return MergedNamespaceSymbol.Create(Me, nsSymbols)
End Function
Public Overrides Function Shrink(namespacesToMerge As IEnumerable(Of NamespaceSymbol)) As NamespaceSymbol
Dim namespaceArray = ArrayBuilder(Of NamespaceSymbol).GetInstance()
namespaceArray.AddRange(namespacesToMerge)
' Currently, if we are just merging 1 namespace, we just return the namespace itself. This is
' by far the most efficient, because it means that we don't create merged namespaces (which have a fair amount
' of memory overhead) unless there is actual merging going on.
Debug.Assert(namespaceArray.Count <> 0)
If namespaceArray.Count = 0 Then
namespaceArray.Free()
Return Me
End If
' New set of parts should be a subset of what we already have
If namespaceArray.Count = 1 Then
Dim result = namespaceArray(0)
namespaceArray.Free()
If _namespacesToMerge.Contains(result) Then
Return result
End If
Throw ExceptionUtilities.Unreachable
End If
Dim lookup = New SmallDictionary(Of NamespaceSymbol, Boolean)()
For Each item In _namespacesToMerge
lookup(item) = False
Next
For Each item In namespaceArray
If Not lookup.TryGetValue(item, Nothing) Then
Debug.Assert(False)
namespaceArray.Free()
Return Me
End If
Next
Return Shrink(namespaceArray.ToImmutableAndFree())
End Function
Private Overloads Function Shrink(namespaceArray As ImmutableArray(Of NamespaceSymbol)) As NamespaceGroupSymbol
Debug.Assert(namespaceArray.Length < _namespacesToMerge.Length)
If namespaceArray.Length >= _namespacesToMerge.Length Then
Debug.Assert(False)
Return Me
End If
If _containingNamespace Is GlobalNamespace Then
Return New NamespaceGroupSymbol(GlobalNamespace, namespaceArray)
End If
Dim parentsArray = ArrayBuilder(Of NamespaceSymbol).GetInstance(namespaceArray.Length)
For Each item In namespaceArray
parentsArray.Add(item.ContainingNamespace)
Next
Return New NamespaceGroupSymbol(DirectCast(_containingNamespace, NamespaceGroupSymbol).Shrink(parentsArray.ToImmutableAndFree()), namespaceArray)
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VSPackage.de.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../VSPackage.resx">
<body>
<trans-unit id="110">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
<trans-unit id="112">
<source>Roslyn Diagnostics</source>
<target state="translated">Roslyn-Diagnose</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/CSharpTest2/Recommendations/SealedKeywordRecommenderTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class SealedKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodInClass()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFieldInClass()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyInClass()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
=> await VerifyAbsenceAsync(@"abstract $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInternal()
=> await VerifyAbsenceAsync(@"static internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInternalStatic()
=> await VerifyAbsenceAsync(@"internal static $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInvalidInternal()
=> await VerifyAbsenceAsync(@"virtual internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
=> await VerifyAbsenceAsync(@"class $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSealed()
=> await VerifyAbsenceAsync(@"sealed $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStatic()
=> await VerifyAbsenceAsync(@"static $$");
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticInInterface()
{
await VerifyKeywordAsync(@"interface C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
=> await VerifyAbsenceAsync(@"delegate $$");
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
abstract $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedOverride()
{
await VerifyKeywordAsync(
@"class C {
override $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInProperty()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterAccessor()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterAccessibility()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterInternal()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; internal $$");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Recommendations
{
public class SealedKeywordRecommenderTests : KeywordRecommenderTests
{
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAtRoot_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterClass_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"class C { }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalStatement_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"System.Console.WriteLine();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalVariableDeclaration_Interactive()
{
await VerifyKeywordAsync(SourceCodeKind.Script,
@"int i = 0;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInUsingAlias()
{
await VerifyAbsenceAsync(
@"using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInGlobalUsingAlias()
{
await VerifyAbsenceAsync(
@"global using Goo = $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInEmptyStatement()
{
await VerifyAbsenceAsync(AddInsideMethod(
@"$$"));
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInCompilationUnit()
{
await VerifyKeywordAsync(
@"$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterExtern()
{
await VerifyKeywordAsync(
@"extern alias Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterUsing()
{
await VerifyKeywordAsync(
@"using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterGlobalUsing()
{
await VerifyKeywordAsync(
@"global using Goo;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNamespace()
{
await VerifyKeywordAsync(
@"namespace N {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFileScopedNamespace()
{
await VerifyKeywordAsync(
@"namespace N;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterTypeDeclaration()
{
await VerifyKeywordAsync(
@"class C {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterDelegateDeclaration()
{
await VerifyKeywordAsync(
@"delegate void Goo();
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterMethodInClass()
{
await VerifyKeywordAsync(
@"class C {
void Goo() {}
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterFieldInClass()
{
await VerifyKeywordAsync(
@"class C {
int i;
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPropertyInClass()
{
await VerifyKeywordAsync(
@"class C {
int i { get; }
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing()
{
await VerifyAbsenceAsync(SourceCodeKind.Regular,
@"$$
global using Goo;");
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/9880"), Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotBeforeGlobalUsing_Interactive()
{
await VerifyAbsenceAsync(SourceCodeKind.Script,
@"$$
global using Goo;");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterAssemblyAttribute()
{
await VerifyKeywordAsync(
@"[assembly: goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterRootAttribute()
{
await VerifyKeywordAsync(
@"[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedAttribute()
{
await VerifyKeywordAsync(
@"class C {
[goo]
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideStruct()
{
await VerifyKeywordAsync(
@"struct S {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideInterface()
{
await VerifyKeywordAsync(@"interface I {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestInsideClass()
{
await VerifyKeywordAsync(
@"class C {
$$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterPartial()
=> await VerifyAbsenceAsync(@"partial $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterAbstract()
=> await VerifyAbsenceAsync(@"abstract $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterInternal()
{
await VerifyKeywordAsync(
@"internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPublic()
{
await VerifyKeywordAsync(
@"public $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStaticInternal()
=> await VerifyAbsenceAsync(@"static internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInternalStatic()
=> await VerifyAbsenceAsync(@"internal static $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterInvalidInternal()
=> await VerifyAbsenceAsync(@"virtual internal $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterClass()
=> await VerifyAbsenceAsync(@"class $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterPrivate()
{
await VerifyKeywordAsync(
@"private $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterSealed()
=> await VerifyAbsenceAsync(@"sealed $$");
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterStatic()
=> await VerifyAbsenceAsync(@"static $$");
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedStatic([CombinatorialValues("class", "struct", "record", "record struct", "record class")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedStaticInInterface()
{
await VerifyKeywordAsync(@"interface C {
static $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedInternal()
{
await VerifyKeywordAsync(
@"class C {
internal $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotAfterDelegate()
=> await VerifyAbsenceAsync(@"delegate $$");
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedAbstract([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
abstract $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedVirtual([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
virtual $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestAfterNestedOverride()
{
await VerifyKeywordAsync(
@"class C {
override $$");
}
[Theory, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
[CombinatorialData]
public async Task TestNotAfterNestedSealed([CombinatorialValues("class", "struct", "record", "record struct", "record class", "interface")] string declarationKind)
{
await VerifyAbsenceAsync(declarationKind + @" C {
sealed $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInProperty()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterAccessor()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterAccessibility()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; protected $$");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)]
public async Task TestNotInPropertyAfterInternal()
{
await VerifyAbsenceAsync(
@"class C {
int Goo { get; internal $$");
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/Core/Portable/xlf/WorkspacesResources.it.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../WorkspacesResources.resx">
<body>
<trans-unit id="A_project_may_not_reference_itself">
<source>A project may not reference itself.</source>
<target state="translated">Un progetto non può fare riferimento a se stesso.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_config_documents_is_not_supported">
<source>Adding analyzer config documents is not supported.</source>
<target state="translated">L'aggiunta di documenti di configurazione dell'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0">
<source>An error occurred while reading the specified configuration file: {0}</source>
<target state="translated">Si è verificato un errore durante la lettura del file di configurazione specificato: {0}</target>
<note />
</trans-unit>
<trans-unit id="CSharp_files">
<source>C# files</source>
<target state="translated">File C#</target>
<note />
</trans-unit>
<trans-unit id="Cannot_apply_action_that_is_not_in_0">
<source>Cannot apply action that is not in '{0}'</source>
<target state="translated">Non è possibile applicare un'azione non presente in '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Changing_analyzer_config_documents_is_not_supported">
<source>Changing analyzer config documents is not supported.</source>
<target state="translated">La modifica di documenti di configurazione dell'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_0_is_not_supported">
<source>Changing document '{0}' is not supported.</source>
<target state="translated">La modifica del documento '{0}' non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution">
<source>CodeAction '{0}' did not produce a changed solution</source>
<target state="translated">L'elemento CodeAction '{0}' non ha generato una soluzione modificata</target>
<note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note>
</trans-unit>
<trans-unit id="Core_EditorConfig_Options">
<source>Core EditorConfig Options</source>
<target state="translated">Opzioni EditorConfig di base</target>
<note />
</trans-unit>
<trans-unit id="DateTimeKind_must_be_Utc">
<source>DateTimeKind must be Utc</source>
<target state="translated">Il valore di DateTimeKind deve essere Utc</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4">
<source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source>
<target state="translated">Il tipo di destinazione deve essere {0}, {1}, {2} o {3}, ma quello specificato è {4}.</target>
<note />
</trans-unit>
<trans-unit id="Document_does_not_support_syntax_trees">
<source>Document does not support syntax trees</source>
<target state="translated">Il documento non supporta alberi di sintassi</target>
<note />
</trans-unit>
<trans-unit id="Error_reading_content_of_source_file_0_1">
<source>Error reading content of source file '{0}' -- '{1}'.</source>
<target state="translated">Si è verificato un errore durante la lettura del contenuto del file di origine '{0}' - '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Rientro e spaziatura</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferenze per nuova riga</target>
<note />
</trans-unit>
<trans-unit id="Only_submission_project_can_reference_submission_projects">
<source>Only submission project can reference submission projects.</source>
<target state="translated">Solo il progetto di invio può fare riferimento a progetti di invio.</target>
<note />
</trans-unit>
<trans-unit id="Options_did_not_come_from_specified_Solution">
<source>Options did not come from specified Solution</source>
<target state="translated">Le opzioni non provengono dalla soluzione specificata</target>
<note />
</trans-unit>
<trans-unit id="Predefined_conversion_from_0_to_1">
<source>Predefined conversion from {0} to {1}.</source>
<target state="translated">Conversione predefinita da {0} a {1}.</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_specified_reference">
<source>Project does not contain specified reference</source>
<target state="translated">Il progetto non contiene il riferimento specificato</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Solo refactoring</target>
<note />
</trans-unit>
<trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories">
<source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source>
<target state="translated">Rimuovere la riga seguente se si vogliono ereditare le impostazioni del file con estensione editorconfig da directory di livello superiore</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_config_documents_is_not_supported">
<source>Removing analyzer config documents is not supported.</source>
<target state="translated">La rimozione di documenti di configurazione dell'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Rename_0_to_1">
<source>Rename '{0}' to '{1}'</source>
<target state="translated">Rinomina '{0}' in '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_does_not_contain_specified_reference">
<source>Solution does not contain specified reference</source>
<target state="translated">La soluzione non contiene il riferimento specificato</target>
<note />
</trans-unit>
<trans-unit id="Symbol_0_is_not_from_source">
<source>Symbol "{0}" is not from source.</source>
<target state="translated">Il simbolo "{0}" non proviene dall'origine.</target>
<note />
</trans-unit>
<trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T">
<source>Documentation comment id must start with E, F, M, N, P or T</source>
<target state="translated">L'ID commento della documentazione deve iniziare con E, F, M, N, P o T</target>
<note />
</trans-unit>
<trans-unit id="Cycle_detected_in_extensions">
<source>Cycle detected in extensions</source>
<target state="translated">È stato rilevato un ciclo nelle estensioni</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1">
<source>Destination type must be a {0}, but given one is {1}.</source>
<target state="translated">Il tipo di destinazione deve essere {0}, ma quello specificato è {1}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2">
<source>Destination type must be a {0} or a {1}, but given one is {2}.</source>
<target state="translated">Il tipo di destinazione deve essere {0} o {1}, ma quello specificato è {2}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3">
<source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source>
<target state="translated">Il tipo di destinazione deve essere {0}, {1} o {2}, ma quello specificato è {3}.</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_location_to_generation_symbol_into">
<source>Could not find location to generation symbol into.</source>
<target state="translated">Non è stata trovata la posizione in cui generare il simbolo.</target>
<note />
</trans-unit>
<trans-unit id="No_location_provided_to_add_statements_to">
<source>No location provided to add statements to.</source>
<target state="translated">Non sono state specificate posizioni in cui aggiungere istruzioni.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_not_in_source">
<source>Destination location was not in source.</source>
<target state="translated">La posizione di destinazione non è inclusa nell'origine.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_from_a_different_tree">
<source>Destination location was from a different tree.</source>
<target state="translated">La posizione di destinazione è in un albero diverso.</target>
<note />
</trans-unit>
<trans-unit id="Node_is_of_the_wrong_type">
<source>Node is of the wrong type.</source>
<target state="translated">Il tipo del nodo è errato.</target>
<note />
</trans-unit>
<trans-unit id="Location_must_be_null_or_from_source">
<source>Location must be null or from source.</source>
<target state="translated">La posizione deve essere Null o derivare dall'origine.</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_source_file_0_in_project_1">
<source>Duplicate source file '{0}' in project '{1}'</source>
<target state="translated">File di origine '{0}' duplicato nel progetto '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Removing_projects_is_not_supported">
<source>Removing projects is not supported.</source>
<target state="translated">La rimozione di progetti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_projects_is_not_supported">
<source>Adding projects is not supported.</source>
<target state="translated">L'aggiunta di progetti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution">
<source>Symbol's project could not be found in the provided solution</source>
<target state="translated">Non è stato possibile trovare il progetto del simbolo nella soluzione specificata</target>
<note />
</trans-unit>
<trans-unit id="Sync_namespace_to_folder_structure">
<source>Sync namespace to folder structure</source>
<target state="translated">Sincronizza lo spazio dei nomi con la struttura di cartelle</target>
<note />
</trans-unit>
<trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed">
<source>The contents of a SourceGeneratedDocument may not be changed.</source>
<target state="translated">Non è possibile modificare il contenuto di un elemento SourceGeneratedDocument.</target>
<note>{locked:SourceGeneratedDocument}</note>
</trans-unit>
<trans-unit id="The_project_already_contains_the_specified_reference">
<source>The project already contains the specified reference.</source>
<target state="translated">Il progetto contiene già il riferimento specificato.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_reference">
<source>The solution already contains the specified reference.</source>
<target state="translated">La soluzione contiene già il riferimento specificato.</target>
<note />
</trans-unit>
<trans-unit id="Unknown">
<source>Unknown</source>
<target state="translated">Unbekannt</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_files">
<source>Visual Basic files</source>
<target state="translated">File Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access">
<source>Adding imports will bring an extension method into scope with the same name as '{0}'</source>
<target state="translated">Quando si aggiungono importazioni, nell'ambito verrà aggiunto un metodo di estensione con lo stesso nome di '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Workspace_error">
<source>Workspace error</source>
<target state="translated">Errore dell'area di lavoro</target>
<note />
</trans-unit>
<trans-unit id="Workspace_is_not_empty">
<source>Workspace is not empty.</source>
<target state="translated">L'area di lavoro non è vuota.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_in_a_different_project">
<source>{0} is in a different project.</source>
<target state="translated">{0} si trova in un progetto diverso.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_part_of_the_workspace">
<source>'{0}' is not part of the workspace.</source>
<target state="translated">'{0}' non fa parte dell'area di lavoro.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_part_of_the_workspace">
<source>'{0}' is already part of the workspace.</source>
<target state="translated">'{0}' fa già parte dell'area di lavoro.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_referenced">
<source>'{0}' is not referenced.</source>
<target state="translated">'{0}' non viene usato come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_referenced">
<source>'{0}' is already referenced.</source>
<target state="translated">'{0}' è già usato come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference">
<source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source>
<target state="translated">L'aggiunta del riferimento al progetto da '{0}' a '{1}' provocherà un riferimento circolare.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_not_referenced">
<source>Metadata is not referenced.</source>
<target state="translated">I metadati non vengono usati come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_already_referenced">
<source>Metadata is already referenced.</source>
<target state="translated">I metadati vengono già usati come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_present">
<source>{0} is not present.</source>
<target state="translated">{0} non è presente.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_present">
<source>{0} is already present.</source>
<target state="translated">{0} è già presente.</target>
<note />
</trans-unit>
<trans-unit id="The_specified_document_is_not_a_version_of_this_document">
<source>The specified document is not a version of this document.</source>
<target state="translated">Il documento specificato non è una versione di questo documento.</target>
<note />
</trans-unit>
<trans-unit id="The_language_0_is_not_supported">
<source>The language '{0}' is not supported.</source>
<target state="translated">Il linguaggio '{0}' non è supportato.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_project">
<source>The solution already contains the specified project.</source>
<target state="translated">La soluzione contiene già il progetto specificato.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_project">
<source>The solution does not contain the specified project.</source>
<target state="translated">La soluzione non contiene il progetto specificato.</target>
<note />
</trans-unit>
<trans-unit id="The_project_already_references_the_target_project">
<source>The project already references the target project.</source>
<target state="translated">Il progetto fa già riferimento al progetto di destinazione.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_document">
<source>The solution already contains the specified document.</source>
<target state="translated">La soluzione contiene già il documento specificato.</target>
<note />
</trans-unit>
<trans-unit id="Temporary_storage_cannot_be_written_more_than_once">
<source>Temporary storage cannot be written more than once.</source>
<target state="translated">L'archivio temporaneo non può essere scritto più di una volta.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_open">
<source>'{0}' is not open.</source>
<target state="translated">'{0}' non è aperto.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Non è possibile specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">È necessario specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="File_was_externally_modified_colon_0">
<source>File was externally modified: {0}.</source>
<target state="translated">Il file è stato modificato esternamente: {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unrecognized_language_name">
<source>Unrecognized language name.</source>
<target state="translated">Nome di linguaggio non riconosciuto.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_metadata_reference_colon_0">
<source>Can't resolve metadata reference: '{0}'.</source>
<target state="translated">Non è possibile risolvere il riferimento ai metadati: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_analyzer_reference_colon_0">
<source>Can't resolve analyzer reference: '{0}'.</source>
<target state="translated">Non è possibile risolvere il riferimento all'analizzatore: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_Project">
<source>Invalid project block, expected "=" after Project.</source>
<target state="translated">Il blocco di progetto non è valido. È previsto "=" dopo Project.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_name">
<source>Invalid project block, expected "," after project name.</source>
<target state="translated">Il blocco di progetto non è valido. È previsto "," dopo il nome del progetto.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_path">
<source>Invalid project block, expected "," after project path.</source>
<target state="translated">Il blocco di progetto non è valido. È previsto "," dopo il percorso del progetto.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0">
<source>Expected {0}.</source>
<target state="translated">È previsto '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="_0_must_be_a_non_null_and_non_empty_string">
<source>"{0}" must be a non-null and non-empty string.</source>
<target state="translated">"{0}" deve essere una stringa non Null e non vuota.</target>
<note />
</trans-unit>
<trans-unit id="Expected_header_colon_0">
<source>Expected header: "{0}".</source>
<target state="translated">È prevista un'intestazione: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Expected_end_of_file">
<source>Expected end-of-file.</source>
<target state="translated">È prevista la fine del file.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0_line">
<source>Expected {0} line.</source>
<target state="translated">È prevista la riga {0}.</target>
<note />
</trans-unit>
<trans-unit id="This_submission_already_references_another_submission_project">
<source>This submission already references another submission project.</source>
<target state="translated">Questo invio fa già riferimento a un altro progetto di invio.</target>
<note />
</trans-unit>
<trans-unit id="_0_still_contains_open_documents">
<source>{0} still contains open documents.</source>
<target state="translated">{0} contiene ancora documenti aperti.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_still_open">
<source>{0} is still open.</source>
<target state="translated">{0} è ancora aperto.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Non è possibile serializzare le matrice con più di una dimensione.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit.</target>
<note />
</trans-unit>
<trans-unit id="Specified_path_must_be_absolute">
<source>Specified path must be absolute.</source>
<target state="translated">Il percorso specificato deve essere assoluto.</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified.</source>
<target state="translated">Il nome può essere semplificato.</target>
<note />
</trans-unit>
<trans-unit id="Unknown_identifier">
<source>Unknown identifier.</source>
<target state="translated">Identificatore sconosciuto.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_generate_code_for_unsupported_operator_0">
<source>Cannot generate code for unsupported operator '{0}'</source>
<target state="translated">Non è possibile generare il codice per l'operatore '{0}' non supportato</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_binary_operator">
<source>Invalid number of parameters for binary operator.</source>
<target state="translated">Il numero di parametri per l'operatore binario non è valido.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_unary_operator">
<source>Invalid number of parameters for unary operator.</source>
<target state="translated">Il numero di parametri per l'operatore unario non è valido.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language">
<source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source>
<target state="translated">Non è possibile aprire il progetto '{0}' perché l'estensione di file '{1}' non è associata a un linguaggio.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported">
<source>Cannot open project '{0}' because the language '{1}' is not supported.</source>
<target state="translated">Non è possibile aprire il progetto '{0}' perché il linguaggio '{1}' non è supportato.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_file_path_colon_0">
<source>Invalid project file path: '{0}'</source>
<target state="translated">Percorso del file di progetto non valido: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_solution_file_path_colon_0">
<source>Invalid solution file path: '{0}'</source>
<target state="translated">Percorso del file di soluzione non valido: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Project_file_not_found_colon_0">
<source>Project file not found: '{0}'</source>
<target state="translated">Il file di progetto non è stato trovato: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_file_not_found_colon_0">
<source>Solution file not found: '{0}'</source>
<target state="translated">Il file di soluzione non è stato trovato: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Unmerged_change_from_project_0">
<source>Unmerged change from project '{0}'</source>
<target state="translated">Modifica senza merge dal progetto '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Added_colon">
<source>Added:</source>
<target state="translated">Aggiunto:</target>
<note />
</trans-unit>
<trans-unit id="After_colon">
<source>After:</source>
<target state="translated">Dopo:</target>
<note />
</trans-unit>
<trans-unit id="Before_colon">
<source>Before:</source>
<target state="translated">Prima:</target>
<note />
</trans-unit>
<trans-unit id="Removed_colon">
<source>Removed:</source>
<target state="translated">Elementi rimossi:</target>
<note />
</trans-unit>
<trans-unit id="Invalid_CodePage_value_colon_0">
<source>Invalid CodePage value: {0}</source>
<target state="translated">Valore di CodePage non valido: {0}</target>
<note />
</trans-unit>
<trans-unit id="Adding_additional_documents_is_not_supported">
<source>Adding additional documents is not supported.</source>
<target state="translated">L'aggiunta di altri documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_references_is_not_supported">
<source>Adding analyzer references is not supported.</source>
<target state="translated">L'aggiunta di riferimenti all'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_documents_is_not_supported">
<source>Adding documents is not supported.</source>
<target state="translated">L'aggiunta di documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_metadata_references_is_not_supported">
<source>Adding metadata references is not supported.</source>
<target state="translated">L'aggiunta di riferimenti ai metadati non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_references_is_not_supported">
<source>Adding project references is not supported.</source>
<target state="translated">L'aggiunta di riferimenti al progetto non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_additional_documents_is_not_supported">
<source>Changing additional documents is not supported.</source>
<target state="translated">La modifica di altri documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_documents_is_not_supported">
<source>Changing documents is not supported.</source>
<target state="translated">La modifica di documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_project_properties_is_not_supported">
<source>Changing project properties is not supported.</source>
<target state="translated">La modifica delle proprietà del progetto non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_additional_documents_is_not_supported">
<source>Removing additional documents is not supported.</source>
<target state="translated">La rimozione di altri documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_references_is_not_supported">
<source>Removing analyzer references is not supported.</source>
<target state="translated">La rimozione di riferimenti all'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_documents_is_not_supported">
<source>Removing documents is not supported.</source>
<target state="translated">La rimozione di documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_metadata_references_is_not_supported">
<source>Removing metadata references is not supported.</source>
<target state="translated">La rimozione di riferimenti ai metadati non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_project_references_is_not_supported">
<source>Removing project references is not supported.</source>
<target state="translated">La rimozione di riferimenti al progetto non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace">
<source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source>
<target state="translated">Per eseguire l'attività, è necessario il servizio di tipo '{0}', che però non è disponibile dall'area di lavoro.</target>
<note />
</trans-unit>
<trans-unit id="At_least_one_diagnostic_must_be_supplied">
<source>At least one diagnostic must be supplied.</source>
<target state="translated">È necessario specificare almeno una diagnostica.</target>
<note />
</trans-unit>
<trans-unit id="Diagnostic_must_have_span_0">
<source>Diagnostic must have span '{0}'</source>
<target state="translated">La diagnostica deve contenere l'elemento span '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Cannot_deserialize_type_0">
<source>Cannot deserialize type '{0}'.</source>
<target state="translated">Non è possibile deserializzare il tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Non è possibile serializzare il tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Il tipo '{0}' non è riconosciuto dal binder di serializzazioni.</target>
<note />
</trans-unit>
<trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1">
<source>Label for node '{0}' is invalid, it must be within [0, {1}).</source>
<target state="translated">L'etichetta del nodo '{0}' non è valida. Deve essere compresa tra [0, {1}).</target>
<note />
</trans-unit>
<trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label">
<source>Matching nodes '{0}' and '{1}' must have the same label.</source>
<target state="translated">I nodi corrispondenti '{0}' e '{1}' devono avere la stessa etichetta.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_new_tree">
<source>Node '{0}' must be contained in the new tree.</source>
<target state="translated">Il nodo '{0}' deve essere presente nel nuovo albero.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_old_tree">
<source>Node '{0}' must be contained in the old tree.</source>
<target state="translated">Il nodo '{0}' deve essere presente nel vecchio albero.</target>
<note />
</trans-unit>
<trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol">
<source>The member '{0}' is not declared within the declaration of the symbol.</source>
<target state="translated">Il membro '{0}' non è dichiarato all'interno della dichiarazione del simbolo.</target>
<note />
</trans-unit>
<trans-unit id="The_position_is_not_within_the_symbol_s_declaration">
<source>The position is not within the symbol's declaration</source>
<target state="translated">La posizione non è compresa nella dichiarazione del simbolo</target>
<note />
</trans-unit>
<trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution">
<source>The symbol '{0}' cannot be located within the current solution.</source>
<target state="translated">Il simbolo '{0}' non è stato trovato nella soluzione corrente.</target>
<note />
</trans-unit>
<trans-unit id="Changing_compilation_options_is_not_supported">
<source>Changing compilation options is not supported.</source>
<target state="translated">La modifica delle opzioni di compilazione non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_parse_options_is_not_supported">
<source>Changing parse options is not supported.</source>
<target state="translated">La modifica delle opzioni di analisi non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="The_node_is_not_part_of_the_tree">
<source>The node is not part of the tree.</source>
<target state="translated">Il nodo non fa parte dell'albero.</target>
<note />
</trans-unit>
<trans-unit id="This_workspace_does_not_support_opening_and_closing_documents">
<source>This workspace does not support opening and closing documents.</source>
<target state="translated">Questa area di lavoro non supporta l'apertura e la chiusura di documenti.</target>
<note />
</trans-unit>
<trans-unit id="Exceptions_colon">
<source>Exceptions:</source>
<target state="translated">Eccezioni:</target>
<note />
</trans-unit>
<trans-unit id="_0_returned_an_uninitialized_ImmutableArray">
<source>'{0}' returned an uninitialized ImmutableArray</source>
<target state="translated">'{0}' ha restituito un elemento ImmutableArray non inizializzato</target>
<note />
</trans-unit>
<trans-unit id="Failure">
<source>Failure</source>
<target state="translated">Errore</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Avviso</target>
<note />
</trans-unit>
<trans-unit id="Enable">
<source>Enable</source>
<target state="translated">Abilita</target>
<note />
</trans-unit>
<trans-unit id="Enable_and_ignore_future_errors">
<source>Enable and ignore future errors</source>
<target state="translated">Abilita e ignora gli errori futuri</target>
<note />
</trans-unit>
<trans-unit id="_0_encountered_an_error_and_has_been_disabled">
<source>'{0}' encountered an error and has been disabled.</source>
<target state="translated">'{0}' ha rilevato un errore ed è stato disabilitato.</target>
<note />
</trans-unit>
<trans-unit id="Show_Stack_Trace">
<source>Show Stack Trace</source>
<target state="translated">Mostra analisi dello stack</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Il flusso è troppo lungo.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto.</target>
<note />
</trans-unit>
<trans-unit id="Async_Method">
<source>Async Method</source>
<target state="translated">Metodo asincrono</target>
<note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note>
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Errore</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">Nessuno</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Suggerimento</target>
<note />
</trans-unit>
<trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2">
<source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source>
<target state="translated">Le dimensioni {1} del file '{0}' sono maggiori di quelle consentite, pari a {2}</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_property_is_not_supported">
<source>Changing document properties is not supported</source>
<target state="translated">La modifica delle proprietà del documento non è supportata</target>
<note />
</trans-unit>
<trans-unit id="dot_NET_Coding_Conventions">
<source>.NET Coding Conventions</source>
<target state="translated">Convenzioni di scrittura codice .NET</target>
<note />
</trans-unit>
<trans-unit id="Variables_captured_colon">
<source>Variables captured:</source>
<target state="translated">Variabili acquisite:</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="it" original="../WorkspacesResources.resx">
<body>
<trans-unit id="A_project_may_not_reference_itself">
<source>A project may not reference itself.</source>
<target state="translated">Un progetto non può fare riferimento a se stesso.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_config_documents_is_not_supported">
<source>Adding analyzer config documents is not supported.</source>
<target state="translated">L'aggiunta di documenti di configurazione dell'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0">
<source>An error occurred while reading the specified configuration file: {0}</source>
<target state="translated">Si è verificato un errore durante la lettura del file di configurazione specificato: {0}</target>
<note />
</trans-unit>
<trans-unit id="CSharp_files">
<source>C# files</source>
<target state="translated">File C#</target>
<note />
</trans-unit>
<trans-unit id="Cannot_apply_action_that_is_not_in_0">
<source>Cannot apply action that is not in '{0}'</source>
<target state="translated">Non è possibile applicare un'azione non presente in '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Changing_analyzer_config_documents_is_not_supported">
<source>Changing analyzer config documents is not supported.</source>
<target state="translated">La modifica di documenti di configurazione dell'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_0_is_not_supported">
<source>Changing document '{0}' is not supported.</source>
<target state="translated">La modifica del documento '{0}' non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution">
<source>CodeAction '{0}' did not produce a changed solution</source>
<target state="translated">L'elemento CodeAction '{0}' non ha generato una soluzione modificata</target>
<note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note>
</trans-unit>
<trans-unit id="Core_EditorConfig_Options">
<source>Core EditorConfig Options</source>
<target state="translated">Opzioni EditorConfig di base</target>
<note />
</trans-unit>
<trans-unit id="DateTimeKind_must_be_Utc">
<source>DateTimeKind must be Utc</source>
<target state="translated">Il valore di DateTimeKind deve essere Utc</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4">
<source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source>
<target state="translated">Il tipo di destinazione deve essere {0}, {1}, {2} o {3}, ma quello specificato è {4}.</target>
<note />
</trans-unit>
<trans-unit id="Document_does_not_support_syntax_trees">
<source>Document does not support syntax trees</source>
<target state="translated">Il documento non supporta alberi di sintassi</target>
<note />
</trans-unit>
<trans-unit id="Error_reading_content_of_source_file_0_1">
<source>Error reading content of source file '{0}' -- '{1}'.</source>
<target state="translated">Si è verificato un errore durante la lettura del contenuto del file di origine '{0}' - '{1}'.</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Rientro e spaziatura</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Preferenze per nuova riga</target>
<note />
</trans-unit>
<trans-unit id="Only_submission_project_can_reference_submission_projects">
<source>Only submission project can reference submission projects.</source>
<target state="translated">Solo il progetto di invio può fare riferimento a progetti di invio.</target>
<note />
</trans-unit>
<trans-unit id="Options_did_not_come_from_specified_Solution">
<source>Options did not come from specified Solution</source>
<target state="translated">Le opzioni non provengono dalla soluzione specificata</target>
<note />
</trans-unit>
<trans-unit id="Predefined_conversion_from_0_to_1">
<source>Predefined conversion from {0} to {1}.</source>
<target state="translated">Conversione predefinita da {0} a {1}.</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_specified_reference">
<source>Project does not contain specified reference</source>
<target state="translated">Il progetto non contiene il riferimento specificato</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Solo refactoring</target>
<note />
</trans-unit>
<trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories">
<source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source>
<target state="translated">Rimuovere la riga seguente se si vogliono ereditare le impostazioni del file con estensione editorconfig da directory di livello superiore</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_config_documents_is_not_supported">
<source>Removing analyzer config documents is not supported.</source>
<target state="translated">La rimozione di documenti di configurazione dell'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Rename_0_to_1">
<source>Rename '{0}' to '{1}'</source>
<target state="translated">Rinomina '{0}' in '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_does_not_contain_specified_reference">
<source>Solution does not contain specified reference</source>
<target state="translated">La soluzione non contiene il riferimento specificato</target>
<note />
</trans-unit>
<trans-unit id="Symbol_0_is_not_from_source">
<source>Symbol "{0}" is not from source.</source>
<target state="translated">Il simbolo "{0}" non proviene dall'origine.</target>
<note />
</trans-unit>
<trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T">
<source>Documentation comment id must start with E, F, M, N, P or T</source>
<target state="translated">L'ID commento della documentazione deve iniziare con E, F, M, N, P o T</target>
<note />
</trans-unit>
<trans-unit id="Cycle_detected_in_extensions">
<source>Cycle detected in extensions</source>
<target state="translated">È stato rilevato un ciclo nelle estensioni</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1">
<source>Destination type must be a {0}, but given one is {1}.</source>
<target state="translated">Il tipo di destinazione deve essere {0}, ma quello specificato è {1}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2">
<source>Destination type must be a {0} or a {1}, but given one is {2}.</source>
<target state="translated">Il tipo di destinazione deve essere {0} o {1}, ma quello specificato è {2}.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3">
<source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source>
<target state="translated">Il tipo di destinazione deve essere {0}, {1} o {2}, ma quello specificato è {3}.</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_location_to_generation_symbol_into">
<source>Could not find location to generation symbol into.</source>
<target state="translated">Non è stata trovata la posizione in cui generare il simbolo.</target>
<note />
</trans-unit>
<trans-unit id="No_location_provided_to_add_statements_to">
<source>No location provided to add statements to.</source>
<target state="translated">Non sono state specificate posizioni in cui aggiungere istruzioni.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_not_in_source">
<source>Destination location was not in source.</source>
<target state="translated">La posizione di destinazione non è inclusa nell'origine.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_from_a_different_tree">
<source>Destination location was from a different tree.</source>
<target state="translated">La posizione di destinazione è in un albero diverso.</target>
<note />
</trans-unit>
<trans-unit id="Node_is_of_the_wrong_type">
<source>Node is of the wrong type.</source>
<target state="translated">Il tipo del nodo è errato.</target>
<note />
</trans-unit>
<trans-unit id="Location_must_be_null_or_from_source">
<source>Location must be null or from source.</source>
<target state="translated">La posizione deve essere Null o derivare dall'origine.</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_source_file_0_in_project_1">
<source>Duplicate source file '{0}' in project '{1}'</source>
<target state="translated">File di origine '{0}' duplicato nel progetto '{1}'</target>
<note />
</trans-unit>
<trans-unit id="Removing_projects_is_not_supported">
<source>Removing projects is not supported.</source>
<target state="translated">La rimozione di progetti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_projects_is_not_supported">
<source>Adding projects is not supported.</source>
<target state="translated">L'aggiunta di progetti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution">
<source>Symbol's project could not be found in the provided solution</source>
<target state="translated">Non è stato possibile trovare il progetto del simbolo nella soluzione specificata</target>
<note />
</trans-unit>
<trans-unit id="Sync_namespace_to_folder_structure">
<source>Sync namespace to folder structure</source>
<target state="translated">Sincronizza lo spazio dei nomi con la struttura di cartelle</target>
<note />
</trans-unit>
<trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed">
<source>The contents of a SourceGeneratedDocument may not be changed.</source>
<target state="translated">Non è possibile modificare il contenuto di un elemento SourceGeneratedDocument.</target>
<note>{locked:SourceGeneratedDocument}</note>
</trans-unit>
<trans-unit id="The_project_already_contains_the_specified_reference">
<source>The project already contains the specified reference.</source>
<target state="translated">Il progetto contiene già il riferimento specificato.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_reference">
<source>The solution already contains the specified reference.</source>
<target state="translated">La soluzione contiene già il riferimento specificato.</target>
<note />
</trans-unit>
<trans-unit id="Unknown">
<source>Unknown</source>
<target state="translated">Unbekannt</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_files">
<source>Visual Basic files</source>
<target state="translated">File Visual Basic</target>
<note />
</trans-unit>
<trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access">
<source>Adding imports will bring an extension method into scope with the same name as '{0}'</source>
<target state="translated">Quando si aggiungono importazioni, nell'ambito verrà aggiunto un metodo di estensione con lo stesso nome di '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Workspace_error">
<source>Workspace error</source>
<target state="translated">Errore dell'area di lavoro</target>
<note />
</trans-unit>
<trans-unit id="Workspace_is_not_empty">
<source>Workspace is not empty.</source>
<target state="translated">L'area di lavoro non è vuota.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_in_a_different_project">
<source>{0} is in a different project.</source>
<target state="translated">{0} si trova in un progetto diverso.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_part_of_the_workspace">
<source>'{0}' is not part of the workspace.</source>
<target state="translated">'{0}' non fa parte dell'area di lavoro.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_part_of_the_workspace">
<source>'{0}' is already part of the workspace.</source>
<target state="translated">'{0}' fa già parte dell'area di lavoro.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_referenced">
<source>'{0}' is not referenced.</source>
<target state="translated">'{0}' non viene usato come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_referenced">
<source>'{0}' is already referenced.</source>
<target state="translated">'{0}' è già usato come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference">
<source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source>
<target state="translated">L'aggiunta del riferimento al progetto da '{0}' a '{1}' provocherà un riferimento circolare.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_not_referenced">
<source>Metadata is not referenced.</source>
<target state="translated">I metadati non vengono usati come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_already_referenced">
<source>Metadata is already referenced.</source>
<target state="translated">I metadati vengono già usati come riferimento.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_present">
<source>{0} is not present.</source>
<target state="translated">{0} non è presente.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_present">
<source>{0} is already present.</source>
<target state="translated">{0} è già presente.</target>
<note />
</trans-unit>
<trans-unit id="The_specified_document_is_not_a_version_of_this_document">
<source>The specified document is not a version of this document.</source>
<target state="translated">Il documento specificato non è una versione di questo documento.</target>
<note />
</trans-unit>
<trans-unit id="The_language_0_is_not_supported">
<source>The language '{0}' is not supported.</source>
<target state="translated">Il linguaggio '{0}' non è supportato.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_project">
<source>The solution already contains the specified project.</source>
<target state="translated">La soluzione contiene già il progetto specificato.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_project">
<source>The solution does not contain the specified project.</source>
<target state="translated">La soluzione non contiene il progetto specificato.</target>
<note />
</trans-unit>
<trans-unit id="The_project_already_references_the_target_project">
<source>The project already references the target project.</source>
<target state="translated">Il progetto fa già riferimento al progetto di destinazione.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_document">
<source>The solution already contains the specified document.</source>
<target state="translated">La soluzione contiene già il documento specificato.</target>
<note />
</trans-unit>
<trans-unit id="Temporary_storage_cannot_be_written_more_than_once">
<source>Temporary storage cannot be written more than once.</source>
<target state="translated">L'archivio temporaneo non può essere scritto più di una volta.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_open">
<source>'{0}' is not open.</source>
<target state="translated">'{0}' non è aperto.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Non è possibile specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">È necessario specificare un nome di linguaggio per questa opzione.</target>
<note />
</trans-unit>
<trans-unit id="File_was_externally_modified_colon_0">
<source>File was externally modified: {0}.</source>
<target state="translated">Il file è stato modificato esternamente: {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unrecognized_language_name">
<source>Unrecognized language name.</source>
<target state="translated">Nome di linguaggio non riconosciuto.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_metadata_reference_colon_0">
<source>Can't resolve metadata reference: '{0}'.</source>
<target state="translated">Non è possibile risolvere il riferimento ai metadati: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_analyzer_reference_colon_0">
<source>Can't resolve analyzer reference: '{0}'.</source>
<target state="translated">Non è possibile risolvere il riferimento all'analizzatore: '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_Project">
<source>Invalid project block, expected "=" after Project.</source>
<target state="translated">Il blocco di progetto non è valido. È previsto "=" dopo Project.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_name">
<source>Invalid project block, expected "," after project name.</source>
<target state="translated">Il blocco di progetto non è valido. È previsto "," dopo il nome del progetto.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_path">
<source>Invalid project block, expected "," after project path.</source>
<target state="translated">Il blocco di progetto non è valido. È previsto "," dopo il percorso del progetto.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0">
<source>Expected {0}.</source>
<target state="translated">È previsto '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="_0_must_be_a_non_null_and_non_empty_string">
<source>"{0}" must be a non-null and non-empty string.</source>
<target state="translated">"{0}" deve essere una stringa non Null e non vuota.</target>
<note />
</trans-unit>
<trans-unit id="Expected_header_colon_0">
<source>Expected header: "{0}".</source>
<target state="translated">È prevista un'intestazione: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Expected_end_of_file">
<source>Expected end-of-file.</source>
<target state="translated">È prevista la fine del file.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0_line">
<source>Expected {0} line.</source>
<target state="translated">È prevista la riga {0}.</target>
<note />
</trans-unit>
<trans-unit id="This_submission_already_references_another_submission_project">
<source>This submission already references another submission project.</source>
<target state="translated">Questo invio fa già riferimento a un altro progetto di invio.</target>
<note />
</trans-unit>
<trans-unit id="_0_still_contains_open_documents">
<source>{0} still contains open documents.</source>
<target state="translated">{0} contiene ancora documenti aperti.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_still_open">
<source>{0} is still open.</source>
<target state="translated">{0} è ancora aperto.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Non è possibile serializzare le matrice con più di una dimensione.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Il valore è troppo grande per essere rappresentato come intero senza segno a 30 bit.</target>
<note />
</trans-unit>
<trans-unit id="Specified_path_must_be_absolute">
<source>Specified path must be absolute.</source>
<target state="translated">Il percorso specificato deve essere assoluto.</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified.</source>
<target state="translated">Il nome può essere semplificato.</target>
<note />
</trans-unit>
<trans-unit id="Unknown_identifier">
<source>Unknown identifier.</source>
<target state="translated">Identificatore sconosciuto.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_generate_code_for_unsupported_operator_0">
<source>Cannot generate code for unsupported operator '{0}'</source>
<target state="translated">Non è possibile generare il codice per l'operatore '{0}' non supportato</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_binary_operator">
<source>Invalid number of parameters for binary operator.</source>
<target state="translated">Il numero di parametri per l'operatore binario non è valido.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_unary_operator">
<source>Invalid number of parameters for unary operator.</source>
<target state="translated">Il numero di parametri per l'operatore unario non è valido.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language">
<source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source>
<target state="translated">Non è possibile aprire il progetto '{0}' perché l'estensione di file '{1}' non è associata a un linguaggio.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported">
<source>Cannot open project '{0}' because the language '{1}' is not supported.</source>
<target state="translated">Non è possibile aprire il progetto '{0}' perché il linguaggio '{1}' non è supportato.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_file_path_colon_0">
<source>Invalid project file path: '{0}'</source>
<target state="translated">Percorso del file di progetto non valido: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Invalid_solution_file_path_colon_0">
<source>Invalid solution file path: '{0}'</source>
<target state="translated">Percorso del file di soluzione non valido: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Project_file_not_found_colon_0">
<source>Project file not found: '{0}'</source>
<target state="translated">Il file di progetto non è stato trovato: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Solution_file_not_found_colon_0">
<source>Solution file not found: '{0}'</source>
<target state="translated">Il file di soluzione non è stato trovato: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Unmerged_change_from_project_0">
<source>Unmerged change from project '{0}'</source>
<target state="translated">Modifica senza merge dal progetto '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Added_colon">
<source>Added:</source>
<target state="translated">Aggiunto:</target>
<note />
</trans-unit>
<trans-unit id="After_colon">
<source>After:</source>
<target state="translated">Dopo:</target>
<note />
</trans-unit>
<trans-unit id="Before_colon">
<source>Before:</source>
<target state="translated">Prima:</target>
<note />
</trans-unit>
<trans-unit id="Removed_colon">
<source>Removed:</source>
<target state="translated">Elementi rimossi:</target>
<note />
</trans-unit>
<trans-unit id="Invalid_CodePage_value_colon_0">
<source>Invalid CodePage value: {0}</source>
<target state="translated">Valore di CodePage non valido: {0}</target>
<note />
</trans-unit>
<trans-unit id="Adding_additional_documents_is_not_supported">
<source>Adding additional documents is not supported.</source>
<target state="translated">L'aggiunta di altri documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_references_is_not_supported">
<source>Adding analyzer references is not supported.</source>
<target state="translated">L'aggiunta di riferimenti all'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_documents_is_not_supported">
<source>Adding documents is not supported.</source>
<target state="translated">L'aggiunta di documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_metadata_references_is_not_supported">
<source>Adding metadata references is not supported.</source>
<target state="translated">L'aggiunta di riferimenti ai metadati non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_references_is_not_supported">
<source>Adding project references is not supported.</source>
<target state="translated">L'aggiunta di riferimenti al progetto non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_additional_documents_is_not_supported">
<source>Changing additional documents is not supported.</source>
<target state="translated">La modifica di altri documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_documents_is_not_supported">
<source>Changing documents is not supported.</source>
<target state="translated">La modifica di documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_project_properties_is_not_supported">
<source>Changing project properties is not supported.</source>
<target state="translated">La modifica delle proprietà del progetto non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_additional_documents_is_not_supported">
<source>Removing additional documents is not supported.</source>
<target state="translated">La rimozione di altri documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_references_is_not_supported">
<source>Removing analyzer references is not supported.</source>
<target state="translated">La rimozione di riferimenti all'analizzatore non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_documents_is_not_supported">
<source>Removing documents is not supported.</source>
<target state="translated">La rimozione di documenti non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_metadata_references_is_not_supported">
<source>Removing metadata references is not supported.</source>
<target state="translated">La rimozione di riferimenti ai metadati non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Removing_project_references_is_not_supported">
<source>Removing project references is not supported.</source>
<target state="translated">La rimozione di riferimenti al progetto non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace">
<source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source>
<target state="translated">Per eseguire l'attività, è necessario il servizio di tipo '{0}', che però non è disponibile dall'area di lavoro.</target>
<note />
</trans-unit>
<trans-unit id="At_least_one_diagnostic_must_be_supplied">
<source>At least one diagnostic must be supplied.</source>
<target state="translated">È necessario specificare almeno una diagnostica.</target>
<note />
</trans-unit>
<trans-unit id="Diagnostic_must_have_span_0">
<source>Diagnostic must have span '{0}'</source>
<target state="translated">La diagnostica deve contenere l'elemento span '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Cannot_deserialize_type_0">
<source>Cannot deserialize type '{0}'.</source>
<target state="translated">Non è possibile deserializzare il tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Non è possibile serializzare il tipo '{0}'.</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Il tipo '{0}' non è riconosciuto dal binder di serializzazioni.</target>
<note />
</trans-unit>
<trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1">
<source>Label for node '{0}' is invalid, it must be within [0, {1}).</source>
<target state="translated">L'etichetta del nodo '{0}' non è valida. Deve essere compresa tra [0, {1}).</target>
<note />
</trans-unit>
<trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label">
<source>Matching nodes '{0}' and '{1}' must have the same label.</source>
<target state="translated">I nodi corrispondenti '{0}' e '{1}' devono avere la stessa etichetta.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_new_tree">
<source>Node '{0}' must be contained in the new tree.</source>
<target state="translated">Il nodo '{0}' deve essere presente nel nuovo albero.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_old_tree">
<source>Node '{0}' must be contained in the old tree.</source>
<target state="translated">Il nodo '{0}' deve essere presente nel vecchio albero.</target>
<note />
</trans-unit>
<trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol">
<source>The member '{0}' is not declared within the declaration of the symbol.</source>
<target state="translated">Il membro '{0}' non è dichiarato all'interno della dichiarazione del simbolo.</target>
<note />
</trans-unit>
<trans-unit id="The_position_is_not_within_the_symbol_s_declaration">
<source>The position is not within the symbol's declaration</source>
<target state="translated">La posizione non è compresa nella dichiarazione del simbolo</target>
<note />
</trans-unit>
<trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution">
<source>The symbol '{0}' cannot be located within the current solution.</source>
<target state="translated">Il simbolo '{0}' non è stato trovato nella soluzione corrente.</target>
<note />
</trans-unit>
<trans-unit id="Changing_compilation_options_is_not_supported">
<source>Changing compilation options is not supported.</source>
<target state="translated">La modifica delle opzioni di compilazione non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="Changing_parse_options_is_not_supported">
<source>Changing parse options is not supported.</source>
<target state="translated">La modifica delle opzioni di analisi non è supportata.</target>
<note />
</trans-unit>
<trans-unit id="The_node_is_not_part_of_the_tree">
<source>The node is not part of the tree.</source>
<target state="translated">Il nodo non fa parte dell'albero.</target>
<note />
</trans-unit>
<trans-unit id="This_workspace_does_not_support_opening_and_closing_documents">
<source>This workspace does not support opening and closing documents.</source>
<target state="translated">Questa area di lavoro non supporta l'apertura e la chiusura di documenti.</target>
<note />
</trans-unit>
<trans-unit id="Exceptions_colon">
<source>Exceptions:</source>
<target state="translated">Eccezioni:</target>
<note />
</trans-unit>
<trans-unit id="_0_returned_an_uninitialized_ImmutableArray">
<source>'{0}' returned an uninitialized ImmutableArray</source>
<target state="translated">'{0}' ha restituito un elemento ImmutableArray non inizializzato</target>
<note />
</trans-unit>
<trans-unit id="Failure">
<source>Failure</source>
<target state="translated">Errore</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Avviso</target>
<note />
</trans-unit>
<trans-unit id="Enable">
<source>Enable</source>
<target state="translated">Abilita</target>
<note />
</trans-unit>
<trans-unit id="Enable_and_ignore_future_errors">
<source>Enable and ignore future errors</source>
<target state="translated">Abilita e ignora gli errori futuri</target>
<note />
</trans-unit>
<trans-unit id="_0_encountered_an_error_and_has_been_disabled">
<source>'{0}' encountered an error and has been disabled.</source>
<target state="translated">'{0}' ha rilevato un errore ed è stato disabilitato.</target>
<note />
</trans-unit>
<trans-unit id="Show_Stack_Trace">
<source>Show Stack Trace</source>
<target state="translated">Mostra analisi dello stack</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Il flusso è troppo lungo.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Il numero di valori letto dal lettore di deserializzazioni per '{0}' non è corretto.</target>
<note />
</trans-unit>
<trans-unit id="Async_Method">
<source>Async Method</source>
<target state="translated">Metodo asincrono</target>
<note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note>
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Errore</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">Nessuno</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Suggerimento</target>
<note />
</trans-unit>
<trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2">
<source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source>
<target state="translated">Le dimensioni {1} del file '{0}' sono maggiori di quelle consentite, pari a {2}</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_property_is_not_supported">
<source>Changing document properties is not supported</source>
<target state="translated">La modifica delle proprietà del documento non è supportata</target>
<note />
</trans-unit>
<trans-unit id="dot_NET_Coding_Conventions">
<source>.NET Coding Conventions</source>
<target state="translated">Convenzioni di scrittura codice .NET</target>
<note />
</trans-unit>
<trans-unit id="Variables_captured_colon">
<source>Variables captured:</source>
<target state="translated">Variabili acquisite:</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/LanguageServer/ProtocolUnitTests/SemanticTokens/SemanticTokensTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens
{
public class SemanticTokensTests : AbstractSemanticTokensTests
{
[Fact]
public async Task TestGetSemanticTokensAsync()
{
var markup =
@"{|caret:|}// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
var expectedResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false);
Assert.Equal(expectedResults.Data, results.Data);
Assert.Equal(expectedResults.ResultId, results.ResultId);
}
/// <summary>
/// Tests all three handlers in succession and makes sure we receive the expected result at each stage.
/// </summary>
[Fact]
public async Task TestAllHandlersAsync()
{
var markup =
@"{|caret:|}// Comment
static class C { }
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].First();
// 1. Range handler
var range = new LSP.Range { Start = new Position(1, 0), End = new Position(2, 0) };
var rangeResults = await RunGetSemanticTokensRangeAsync(testLspServer, caretLocation, range);
var expectedRangeResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, rangeResults.Data!).ConfigureAwait(false);
Assert.Equal(expectedRangeResults.Data, rangeResults.Data);
Assert.Equal(expectedRangeResults.ResultId, rangeResults.ResultId);
Assert.True(rangeResults is RoslynSemanticTokens);
// 2. Whole document handler
var wholeDocResults = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
var expectedWholeDocResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "2"
};
await VerifyNoMultiLineTokens(testLspServer, wholeDocResults.Data!).ConfigureAwait(false);
Assert.Equal(expectedWholeDocResults.Data, wholeDocResults.Data);
Assert.Equal(expectedWholeDocResults.ResultId, wholeDocResults.ResultId);
Assert.True(wholeDocResults is RoslynSemanticTokens);
// 3. Edits handler - insert newline at beginning of file
var newMarkup = @"
// Comment
static class C { }
";
UpdateDocumentText(newMarkup, testLspServer.TestWorkspace);
var editResults = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "2");
var expectedEdit = new LSP.SemanticTokensEdit { Start = 0, DeleteCount = 1, Data = new int[] { 1 } };
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)editResults).Edits.First());
Assert.Equal("3", ((LSP.SemanticTokensDelta)editResults).ResultId);
Assert.True((LSP.SemanticTokensDelta)editResults is RoslynSemanticTokensDelta);
// 4. Edits handler - no changes (ResultId should remain same)
var editResultsNoChange = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "3");
Assert.Equal("3", ((LSP.SemanticTokensDelta)editResultsNoChange).ResultId);
Assert.True((LSP.SemanticTokensDelta)editResultsNoChange is RoslynSemanticTokensDelta);
// 5. Re-request whole document handler (may happen if LSP runs into an error)
var wholeDocResults2 = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
var expectedWholeDocResults2 = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
1, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "4"
};
await VerifyNoMultiLineTokens(testLspServer, wholeDocResults2.Data!).ConfigureAwait(false);
Assert.Equal(expectedWholeDocResults2.Data, wholeDocResults2.Data);
Assert.Equal(expectedWholeDocResults2.ResultId, wholeDocResults2.ResultId);
Assert.True(wholeDocResults2 is RoslynSemanticTokens);
}
[Fact]
public async Task TestGetSemanticTokensMultiLineCommentAsync()
{
var markup =
@"{|caret:|}class C { /* one
two
three */ }
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
var expectedResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '/* one'
1, 0, 3, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'two'
1, 0, 8, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'three */'
0, 9, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false);
Assert.Equal(expectedResults.Data, results.Data);
Assert.Equal(expectedResults.ResultId, results.ResultId);
}
[Fact]
public async Task TestGetSemanticTokensStringLiteralAsync()
{
var markup =
@"{|caret:|}class C
{
void M()
{
var x = @""one
two """"
three"";
}
}
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
var expectedResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C'
1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
1, 4, 4, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'void'
0, 5, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.MethodName], 0, // 'M'
0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '('
0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ')'
1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
1, 8, 3, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Keyword], 0, // 'var'
0, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.LocalName], 0, // 'x'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Operator], 0, // '='
0, 2, 5, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // '@"one'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'two'
0, 4, 2, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.StringEscapeCharacter], 0, // '""'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'three"'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ';'
1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false);
Assert.Equal(expectedResults.Data, results.Data);
Assert.Equal(expectedResults.ResultId, results.ResultId);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable enable
using System.Linq;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.LanguageServer.Handler.SemanticTokens;
using Microsoft.VisualStudio.LanguageServer.Protocol;
using Xunit;
using LSP = Microsoft.VisualStudio.LanguageServer.Protocol;
namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.SemanticTokens
{
public class SemanticTokensTests : AbstractSemanticTokensTests
{
[Fact]
public async Task TestGetSemanticTokensAsync()
{
var markup =
@"{|caret:|}// Comment
static class C { }";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
var expectedResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false);
Assert.Equal(expectedResults.Data, results.Data);
Assert.Equal(expectedResults.ResultId, results.ResultId);
}
/// <summary>
/// Tests all three handlers in succession and makes sure we receive the expected result at each stage.
/// </summary>
[Fact]
public async Task TestAllHandlersAsync()
{
var markup =
@"{|caret:|}// Comment
static class C { }
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var caretLocation = locations["caret"].First();
// 1. Range handler
var range = new LSP.Range { Start = new Position(1, 0), End = new Position(2, 0) };
var rangeResults = await RunGetSemanticTokensRangeAsync(testLspServer, caretLocation, range);
var expectedRangeResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, rangeResults.Data!).ConfigureAwait(false);
Assert.Equal(expectedRangeResults.Data, rangeResults.Data);
Assert.Equal(expectedRangeResults.ResultId, rangeResults.ResultId);
Assert.True(rangeResults is RoslynSemanticTokens);
// 2. Whole document handler
var wholeDocResults = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
var expectedWholeDocResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "2"
};
await VerifyNoMultiLineTokens(testLspServer, wholeDocResults.Data!).ConfigureAwait(false);
Assert.Equal(expectedWholeDocResults.Data, wholeDocResults.Data);
Assert.Equal(expectedWholeDocResults.ResultId, wholeDocResults.ResultId);
Assert.True(wholeDocResults is RoslynSemanticTokens);
// 3. Edits handler - insert newline at beginning of file
var newMarkup = @"
// Comment
static class C { }
";
UpdateDocumentText(newMarkup, testLspServer.TestWorkspace);
var editResults = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "2");
var expectedEdit = new LSP.SemanticTokensEdit { Start = 0, DeleteCount = 1, Data = new int[] { 1 } };
Assert.Equal(expectedEdit, ((LSP.SemanticTokensDelta)editResults).Edits.First());
Assert.Equal("3", ((LSP.SemanticTokensDelta)editResults).ResultId);
Assert.True((LSP.SemanticTokensDelta)editResults is RoslynSemanticTokensDelta);
// 4. Edits handler - no changes (ResultId should remain same)
var editResultsNoChange = await RunGetSemanticTokensEditsAsync(testLspServer, caretLocation, previousResultId: "3");
Assert.Equal("3", ((LSP.SemanticTokensDelta)editResultsNoChange).ResultId);
Assert.True((LSP.SemanticTokensDelta)editResultsNoChange is RoslynSemanticTokensDelta);
// 5. Re-request whole document handler (may happen if LSP runs into an error)
var wholeDocResults2 = await RunGetSemanticTokensAsync(testLspServer, caretLocation);
var expectedWholeDocResults2 = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
1, 0, 10, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '// Comment'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'static'
0, 7, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], (int)TokenModifiers.Static, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "4"
};
await VerifyNoMultiLineTokens(testLspServer, wholeDocResults2.Data!).ConfigureAwait(false);
Assert.Equal(expectedWholeDocResults2.Data, wholeDocResults2.Data);
Assert.Equal(expectedWholeDocResults2.ResultId, wholeDocResults2.ResultId);
Assert.True(wholeDocResults2 is RoslynSemanticTokens);
}
[Fact]
public async Task TestGetSemanticTokensMultiLineCommentAsync()
{
var markup =
@"{|caret:|}class C { /* one
two
three */ }
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
var expectedResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
0, 2, 6, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // '/* one'
1, 0, 3, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'two'
1, 0, 8, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Comment], 0, // 'three */'
0, 9, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false);
Assert.Equal(expectedResults.Data, results.Data);
Assert.Equal(expectedResults.ResultId, results.ResultId);
}
[Fact]
public async Task TestGetSemanticTokensStringLiteralAsync()
{
var markup =
@"{|caret:|}class C
{
void M()
{
var x = @""one
two """"
three"";
}
}
";
using var testLspServer = CreateTestLspServer(markup, out var locations);
var results = await RunGetSemanticTokensAsync(testLspServer, locations["caret"].First());
var expectedResults = new LSP.SemanticTokens
{
Data = new int[]
{
// Line | Char | Len | Token type | Modifier
0, 0, 5, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'class'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.ClassName], 0, // 'C'
1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
1, 4, 4, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Keyword], 0, // 'void'
0, 5, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.MethodName], 0, // 'M'
0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '('
0, 1, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ')'
1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '{'
1, 8, 3, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Keyword], 0, // 'var'
0, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.LocalName], 0, // 'x'
0, 2, 1, SemanticTokensCache.TokenTypeToIndex[LSP.SemanticTokenTypes.Operator], 0, // '='
0, 2, 5, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // '@"one'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'two'
0, 4, 2, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.StringEscapeCharacter], 0, // '""'
1, 0, 6, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.VerbatimStringLiteral], 0, // 'three"'
0, 6, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // ';'
1, 4, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
1, 0, 1, SemanticTokensCache.TokenTypeToIndex[ClassificationTypeNames.Punctuation], 0, // '}'
},
ResultId = "1"
};
await VerifyNoMultiLineTokens(testLspServer, results.Data!).ConfigureAwait(false);
Assert.Equal(expectedResults.Data, results.Data);
Assert.Equal(expectedResults.ResultId, results.ResultId);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/ExpressionEvaluator/Core/Test/ResultProvider/Debugger/Engine/DkmClrValueFlags.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
[Flags]
public enum DkmClrValueFlags
{
None = 0x0,
Error = 0x1,
Synthetic = 0x2,
Void = 0x4,
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .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
{
[Flags]
public enum DkmClrValueFlags
{
None = 0x0,
Error = 0x1,
Synthetic = 0x2,
Void = 0x4,
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/Core/Portable/Completion/MatchResult.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.PatternMatching;
using Roslyn.Utilities;
using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem;
namespace Microsoft.CodeAnalysis.Completion
{
internal readonly struct MatchResult<TEditorCompletionItem>
{
public readonly RoslynCompletionItem RoslynCompletionItem;
public readonly bool MatchedFilterText;
// In certain cases, there'd be no match but we'd still set `MatchedFilterText` to true,
// e.g. when the item is in MRU list. Therefore making this nullable.
public readonly PatternMatch? PatternMatch;
/// <summary>
/// The actual editor completion item associated with this <see cref="RoslynCompletionItem"/>
/// In VS for example, this is the associated VS async completion item.
/// </summary>
public readonly TEditorCompletionItem EditorCompletionItem;
// We want to preserve the original alphabetical order for items with same pattern match score,
// but `ArrayBuilder.Sort` we currently use isn't stable. So we have to add a monotonically increasing
// integer to archieve this.
private readonly int _indexInOriginalSortedOrder;
public MatchResult(
RoslynCompletionItem roslynCompletionItem,
TEditorCompletionItem editorCompletionItem,
bool matchedFilterText,
PatternMatch? patternMatch,
int index)
{
RoslynCompletionItem = roslynCompletionItem;
EditorCompletionItem = editorCompletionItem;
MatchedFilterText = matchedFilterText;
PatternMatch = patternMatch;
_indexInOriginalSortedOrder = index;
}
public static IComparer<MatchResult<TEditorCompletionItem>> SortingComparer => FilterResultSortingComparer.Instance;
private class FilterResultSortingComparer : IComparer<MatchResult<TEditorCompletionItem>>
{
public static FilterResultSortingComparer Instance { get; } = new FilterResultSortingComparer();
// This comparison is used for sorting items in the completion list for the original sorting.
public int Compare(MatchResult<TEditorCompletionItem> x, MatchResult<TEditorCompletionItem> y)
{
var matchX = x.PatternMatch;
var matchY = y.PatternMatch;
if (matchX.HasValue)
{
if (matchY.HasValue)
{
var ret = matchX.Value.CompareTo(matchY.Value);
// We want to preserve the original order for items with same pattern match score.
return ret == 0
? x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder
: ret;
}
return -1;
}
if (matchY.HasValue)
{
return 1;
}
return x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder;
}
}
// This comparison is used in the deletion/backspace scenario for selecting best elements.
public int CompareTo(MatchResult<TEditorCompletionItem> other, string filterText)
=> ComparerWithState.CompareTo(this, other, filterText, s_comparers);
private static readonly ImmutableArray<Func<MatchResult<TEditorCompletionItem>, string, IComparable>> s_comparers =
ImmutableArray.Create<Func<MatchResult<TEditorCompletionItem>, string, IComparable>>(
// Prefer the item that matches a longer prefix of the filter text.
(f, s) => f.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(s),
// If there are "Abc" vs "abc", we should prefer the case typed by user.
(f, s) => f.RoslynCompletionItem.FilterText.GetCaseSensitivePrefixLength(s),
// If the lengths are the same, prefer the one with the higher match priority.
// But only if it's an item that would have been hard selected. We don't want
// to aggressively select an item that was only going to be softly offered.
(f, s) => f.RoslynCompletionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection
? f.RoslynCompletionItem.Rules.MatchPriority
: MatchPriority.Default,
// Prefer Intellicode items.
(f, s) => f.RoslynCompletionItem.IsPreferredItem());
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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 Microsoft.CodeAnalysis.PatternMatching;
using Roslyn.Utilities;
using RoslynCompletionItem = Microsoft.CodeAnalysis.Completion.CompletionItem;
namespace Microsoft.CodeAnalysis.Completion
{
internal readonly struct MatchResult<TEditorCompletionItem>
{
public readonly RoslynCompletionItem RoslynCompletionItem;
public readonly bool MatchedFilterText;
// In certain cases, there'd be no match but we'd still set `MatchedFilterText` to true,
// e.g. when the item is in MRU list. Therefore making this nullable.
public readonly PatternMatch? PatternMatch;
/// <summary>
/// The actual editor completion item associated with this <see cref="RoslynCompletionItem"/>
/// In VS for example, this is the associated VS async completion item.
/// </summary>
public readonly TEditorCompletionItem EditorCompletionItem;
// We want to preserve the original alphabetical order for items with same pattern match score,
// but `ArrayBuilder.Sort` we currently use isn't stable. So we have to add a monotonically increasing
// integer to archieve this.
private readonly int _indexInOriginalSortedOrder;
public MatchResult(
RoslynCompletionItem roslynCompletionItem,
TEditorCompletionItem editorCompletionItem,
bool matchedFilterText,
PatternMatch? patternMatch,
int index)
{
RoslynCompletionItem = roslynCompletionItem;
EditorCompletionItem = editorCompletionItem;
MatchedFilterText = matchedFilterText;
PatternMatch = patternMatch;
_indexInOriginalSortedOrder = index;
}
public static IComparer<MatchResult<TEditorCompletionItem>> SortingComparer => FilterResultSortingComparer.Instance;
private class FilterResultSortingComparer : IComparer<MatchResult<TEditorCompletionItem>>
{
public static FilterResultSortingComparer Instance { get; } = new FilterResultSortingComparer();
// This comparison is used for sorting items in the completion list for the original sorting.
public int Compare(MatchResult<TEditorCompletionItem> x, MatchResult<TEditorCompletionItem> y)
{
var matchX = x.PatternMatch;
var matchY = y.PatternMatch;
if (matchX.HasValue)
{
if (matchY.HasValue)
{
var ret = matchX.Value.CompareTo(matchY.Value);
// We want to preserve the original order for items with same pattern match score.
return ret == 0
? x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder
: ret;
}
return -1;
}
if (matchY.HasValue)
{
return 1;
}
return x._indexInOriginalSortedOrder - y._indexInOriginalSortedOrder;
}
}
// This comparison is used in the deletion/backspace scenario for selecting best elements.
public int CompareTo(MatchResult<TEditorCompletionItem> other, string filterText)
=> ComparerWithState.CompareTo(this, other, filterText, s_comparers);
private static readonly ImmutableArray<Func<MatchResult<TEditorCompletionItem>, string, IComparable>> s_comparers =
ImmutableArray.Create<Func<MatchResult<TEditorCompletionItem>, string, IComparable>>(
// Prefer the item that matches a longer prefix of the filter text.
(f, s) => f.RoslynCompletionItem.FilterText.GetCaseInsensitivePrefixLength(s),
// If there are "Abc" vs "abc", we should prefer the case typed by user.
(f, s) => f.RoslynCompletionItem.FilterText.GetCaseSensitivePrefixLength(s),
// If the lengths are the same, prefer the one with the higher match priority.
// But only if it's an item that would have been hard selected. We don't want
// to aggressively select an item that was only going to be softly offered.
(f, s) => f.RoslynCompletionItem.Rules.SelectionBehavior == CompletionItemSelectionBehavior.HardSelection
? f.RoslynCompletionItem.Rules.MatchPriority
: MatchPriority.Default,
// Prefer Intellicode items.
(f, s) => f.RoslynCompletionItem.IsPreferredItem());
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/Core/Portable/Shared/Utilities/ProgressTracker.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// Utility class that can be used to track the progress of an operation in a threadsafe manner.
/// </summary>
internal class ProgressTracker : IProgressTracker
{
private string _description;
private int _completedItems;
private int _totalItems;
private readonly Action<string, int, int> _updateActionOpt;
public ProgressTracker()
: this(null)
{
}
public ProgressTracker(Action<string, int, int> updateActionOpt)
=> _updateActionOpt = updateActionOpt;
public string Description
{
get => _description;
set
{
_description = value;
Update();
}
}
public int CompletedItems => _completedItems;
public int TotalItems => _totalItems;
public void AddItems(int count)
{
Interlocked.Add(ref _totalItems, count);
Update();
}
public void ItemCompleted()
{
Interlocked.Increment(ref _completedItems);
Update();
}
public void Clear()
{
_totalItems = 0;
_completedItems = 0;
_description = null;
Update();
}
private void Update()
=> _updateActionOpt?.Invoke(_description, _completedItems, _totalItems);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading;
namespace Microsoft.CodeAnalysis.Shared.Utilities
{
/// <summary>
/// Utility class that can be used to track the progress of an operation in a threadsafe manner.
/// </summary>
internal class ProgressTracker : IProgressTracker
{
private string _description;
private int _completedItems;
private int _totalItems;
private readonly Action<string, int, int> _updateActionOpt;
public ProgressTracker()
: this(null)
{
}
public ProgressTracker(Action<string, int, int> updateActionOpt)
=> _updateActionOpt = updateActionOpt;
public string Description
{
get => _description;
set
{
_description = value;
Update();
}
}
public int CompletedItems => _completedItems;
public int TotalItems => _totalItems;
public void AddItems(int count)
{
Interlocked.Add(ref _totalItems, count);
Update();
}
public void ItemCompleted()
{
Interlocked.Increment(ref _completedItems);
Update();
}
public void Clear()
{
_totalItems = 0;
_completedItems = 0;
_description = null;
Update();
}
private void Update()
=> _updateActionOpt?.Invoke(_description, _completedItems, _totalItems);
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Interactive/Host/xlf/InteractiveHostResources.zh-Hant.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../InteractiveHostResources.resx">
<body>
<trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying">
<source>Attempt to connect to process #{0} failed, retrying ...</source>
<target state="translated">嘗試連接到處理序 #{0} 失敗,正在重試...</target>
<note />
</trans-unit>
<trans-unit id="Cannot_resolve_reference_0">
<source>Cannot resolve reference '{0}'.</source>
<target state="translated">無法解析參考 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution">
<source>Failed to create a remote process for interactive code execution: '{0}'</source>
<target state="translated">無法為互動式程式碼執行建立遠端處理序: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_initialize_remote_interactive_process">
<source>Failed to initialize remote interactive process.</source>
<target state="translated">無法初始化遠端互動式處理序。</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon">
<source>Failed to launch '{0}' process (exit code: {1}) with output: </source>
<target state="translated">無法啟動 '{0}' 處理序 (結束代碼: {1}),輸出如下: </target>
<note />
</trans-unit>
<trans-unit id="Hosting_process_exited_with_exit_code_0">
<source>Hosting process exited with exit code {0}.</source>
<target state="translated">裝載處理序已結束,結束代碼為 {0}。</target>
<note />
</trans-unit>
<trans-unit id="Interactive_Host_not_initialized">
<source>Interactive Host not initialized.</source>
<target state="translated">未初始化互動式主機。</target>
<note />
</trans-unit>
<trans-unit id="Loading_context_from_0">
<source>Loading context from '{0}'.</source>
<target state="translated">正在載入 '{0}' 的內容。</target>
<note />
</trans-unit>
<trans-unit id="Searched_in_directories_colon">
<source>Searched in directories:</source>
<target state="translated">在下列目錄中搜尋:</target>
<note />
</trans-unit>
<trans-unit id="Searched_in_directory_colon">
<source>Searched in directory:</source>
<target state="translated">在下列目錄中搜尋:</target>
<note />
</trans-unit>
<trans-unit id="Specified_file_not_found">
<source>Specified file not found.</source>
<target state="translated">找不到指定的檔案</target>
<note />
</trans-unit>
<trans-unit id="Specified_file_not_found_colon_0">
<source>Specified file not found: {0}</source>
<target state="translated">找不到指定的檔案: {0}</target>
<note />
</trans-unit>
<trans-unit id="Type_Sharphelp_for_more_information">
<source>Type "#help" for more information.</source>
<target state="translated">如需詳細資訊,請輸入 "#help"。</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_create_hosting_process">
<source>Unable to create hosting process.</source>
<target state="translated">無法建立裝載處理序。</target>
<note />
</trans-unit>
<trans-unit id="plus_additional_0_1">
<source> + additional {0} {1}</source>
<target state="translated"> + 額外的 {0} {1}</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="zh-Hant" original="../InteractiveHostResources.resx">
<body>
<trans-unit id="Attempt_to_connect_to_process_Sharp_0_failed_retrying">
<source>Attempt to connect to process #{0} failed, retrying ...</source>
<target state="translated">嘗試連接到處理序 #{0} 失敗,正在重試...</target>
<note />
</trans-unit>
<trans-unit id="Cannot_resolve_reference_0">
<source>Cannot resolve reference '{0}'.</source>
<target state="translated">無法解析參考 '{0}'。</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_create_a_remote_process_for_interactive_code_execution">
<source>Failed to create a remote process for interactive code execution: '{0}'</source>
<target state="translated">無法為互動式程式碼執行建立遠端處理序: '{0}'</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_initialize_remote_interactive_process">
<source>Failed to initialize remote interactive process.</source>
<target state="translated">無法初始化遠端互動式處理序。</target>
<note />
</trans-unit>
<trans-unit id="Failed_to_launch_0_process_exit_code_colon_1_with_output_colon">
<source>Failed to launch '{0}' process (exit code: {1}) with output: </source>
<target state="translated">無法啟動 '{0}' 處理序 (結束代碼: {1}),輸出如下: </target>
<note />
</trans-unit>
<trans-unit id="Hosting_process_exited_with_exit_code_0">
<source>Hosting process exited with exit code {0}.</source>
<target state="translated">裝載處理序已結束,結束代碼為 {0}。</target>
<note />
</trans-unit>
<trans-unit id="Interactive_Host_not_initialized">
<source>Interactive Host not initialized.</source>
<target state="translated">未初始化互動式主機。</target>
<note />
</trans-unit>
<trans-unit id="Loading_context_from_0">
<source>Loading context from '{0}'.</source>
<target state="translated">正在載入 '{0}' 的內容。</target>
<note />
</trans-unit>
<trans-unit id="Searched_in_directories_colon">
<source>Searched in directories:</source>
<target state="translated">在下列目錄中搜尋:</target>
<note />
</trans-unit>
<trans-unit id="Searched_in_directory_colon">
<source>Searched in directory:</source>
<target state="translated">在下列目錄中搜尋:</target>
<note />
</trans-unit>
<trans-unit id="Specified_file_not_found">
<source>Specified file not found.</source>
<target state="translated">找不到指定的檔案</target>
<note />
</trans-unit>
<trans-unit id="Specified_file_not_found_colon_0">
<source>Specified file not found: {0}</source>
<target state="translated">找不到指定的檔案: {0}</target>
<note />
</trans-unit>
<trans-unit id="Type_Sharphelp_for_more_information">
<source>Type "#help" for more information.</source>
<target state="translated">如需詳細資訊,請輸入 "#help"。</target>
<note />
</trans-unit>
<trans-unit id="Unable_to_create_hosting_process">
<source>Unable to create hosting process.</source>
<target state="translated">無法建立裝載處理序。</target>
<note />
</trans-unit>
<trans-unit id="plus_additional_0_1">
<source> + additional {0} {1}</source>
<target state="translated"> + 額外的 {0} {1}</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/Core/Portable/xlf/WorkspacesResources.de.xlf | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../WorkspacesResources.resx">
<body>
<trans-unit id="A_project_may_not_reference_itself">
<source>A project may not reference itself.</source>
<target state="translated">Ein Projekt darf nicht auf sich selbst verweisen.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_config_documents_is_not_supported">
<source>Adding analyzer config documents is not supported.</source>
<target state="translated">Das Hinzufügen von Konfigurationsdokumenten des Analysetools wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0">
<source>An error occurred while reading the specified configuration file: {0}</source>
<target state="translated">Beim Lesen der angegebenen Konfigurationsdatei ist ein Fehler aufgetreten: {0}</target>
<note />
</trans-unit>
<trans-unit id="CSharp_files">
<source>C# files</source>
<target state="translated">C#-Dateien</target>
<note />
</trans-unit>
<trans-unit id="Cannot_apply_action_that_is_not_in_0">
<source>Cannot apply action that is not in '{0}'</source>
<target state="translated">Es können nur in "{0}" enthaltene Aktionen angewendet werden.</target>
<note />
</trans-unit>
<trans-unit id="Changing_analyzer_config_documents_is_not_supported">
<source>Changing analyzer config documents is not supported.</source>
<target state="translated">Das Ändern von Konfigurationsdokumenten des Analysetools wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_0_is_not_supported">
<source>Changing document '{0}' is not supported.</source>
<target state="translated">Das Ändern des Dokuments "{0}" wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution">
<source>CodeAction '{0}' did not produce a changed solution</source>
<target state="translated">Durch CodeAction "{0}" wurde keine geänderte Lösung erstellt.</target>
<note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note>
</trans-unit>
<trans-unit id="Core_EditorConfig_Options">
<source>Core EditorConfig Options</source>
<target state="translated">Wichtige EditorConfig-Optionen</target>
<note />
</trans-unit>
<trans-unit id="DateTimeKind_must_be_Utc">
<source>DateTimeKind must be Utc</source>
<target state="translated">"DateTimeKind" muss UTC sein.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4">
<source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source>
<target state="translated">Der Zieltyp muss "{0}", "{1}", "{2}" oder "{3}" lauten. Es wurde jedoch "{4}" angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Document_does_not_support_syntax_trees">
<source>Document does not support syntax trees</source>
<target state="translated">Das Dokument unterstützt keine Syntaxstrukturen.</target>
<note />
</trans-unit>
<trans-unit id="Error_reading_content_of_source_file_0_1">
<source>Error reading content of source file '{0}' -- '{1}'.</source>
<target state="translated">Fehler beim Lesen des Inhalts der Quelldatei "{0}": "{1}".</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Einzüge und Abstände</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Einstellungen für neue Zeilen</target>
<note />
</trans-unit>
<trans-unit id="Only_submission_project_can_reference_submission_projects">
<source>Only submission project can reference submission projects.</source>
<target state="translated">Nur ein Übermittlungsprojekt kann auf Übermittlungsprojekte verweisen.</target>
<note />
</trans-unit>
<trans-unit id="Options_did_not_come_from_specified_Solution">
<source>Options did not come from specified Solution</source>
<target state="translated">Optionen stammen nicht aus der angegebenen Projektmappe.</target>
<note />
</trans-unit>
<trans-unit id="Predefined_conversion_from_0_to_1">
<source>Predefined conversion from {0} to {1}.</source>
<target state="translated">Vordefinierte Konvertierung von "{0}" in "{1}".</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_specified_reference">
<source>Project does not contain specified reference</source>
<target state="translated">Der angegebene Verweis ist im Projekt nicht enthalten.</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Nur Refactoring</target>
<note />
</trans-unit>
<trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories">
<source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source>
<target state="translated">Entfernen Sie die folgende Zeile, wenn Sie EDITORCONFIG-Einstellungen von höheren Verzeichnissen vererben möchten.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_config_documents_is_not_supported">
<source>Removing analyzer config documents is not supported.</source>
<target state="translated">Das Entfernen von Konfigurationsdokumenten des Analysetools wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Rename_0_to_1">
<source>Rename '{0}' to '{1}'</source>
<target state="translated">"{0}" in "{1}" umbenennen</target>
<note />
</trans-unit>
<trans-unit id="Solution_does_not_contain_specified_reference">
<source>Solution does not contain specified reference</source>
<target state="translated">Der angegebene Verweis ist nicht in der Projektmappe enthalten.</target>
<note />
</trans-unit>
<trans-unit id="Symbol_0_is_not_from_source">
<source>Symbol "{0}" is not from source.</source>
<target state="translated">Symbol "{0}" ist nicht aus Quelle.</target>
<note />
</trans-unit>
<trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T">
<source>Documentation comment id must start with E, F, M, N, P or T</source>
<target state="translated">Dokumentationskommentar-ID muss mit E, F, M, N, P oder T beginnen</target>
<note />
</trans-unit>
<trans-unit id="Cycle_detected_in_extensions">
<source>Cycle detected in extensions</source>
<target state="translated">Zyklus in Erweiterungen entdeckt</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1">
<source>Destination type must be a {0}, but given one is {1}.</source>
<target state="translated">Zieltyp muss {0} sein. Es wurde jedoch {1} angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2">
<source>Destination type must be a {0} or a {1}, but given one is {2}.</source>
<target state="translated">Zieltyp muss {0} oder {1} sein. Es wurde jedoch {2} angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3">
<source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source>
<target state="translated">Zieltyp muss {0}, {1} oder {2} sein. Es wurde jedoch {3} angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_location_to_generation_symbol_into">
<source>Could not find location to generation symbol into.</source>
<target state="translated">Konnte keinen Ort finden, in den das Symbol generiert werden kann.</target>
<note />
</trans-unit>
<trans-unit id="No_location_provided_to_add_statements_to">
<source>No location provided to add statements to.</source>
<target state="translated">Kein Ort angegeben, zu dem Anweisungen hinzugefügt werden.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_not_in_source">
<source>Destination location was not in source.</source>
<target state="translated">Zielort war nicht in Quelle.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_from_a_different_tree">
<source>Destination location was from a different tree.</source>
<target state="translated">Zielort stammt aus anderem Baum.</target>
<note />
</trans-unit>
<trans-unit id="Node_is_of_the_wrong_type">
<source>Node is of the wrong type.</source>
<target state="translated">Knoten hat den falschen Typ.</target>
<note />
</trans-unit>
<trans-unit id="Location_must_be_null_or_from_source">
<source>Location must be null or from source.</source>
<target state="translated">Ort muss null oder von Quelle sein.</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_source_file_0_in_project_1">
<source>Duplicate source file '{0}' in project '{1}'</source>
<target state="translated">Doppelte Quelldatei "{0}" in Projekt "{1}"</target>
<note />
</trans-unit>
<trans-unit id="Removing_projects_is_not_supported">
<source>Removing projects is not supported.</source>
<target state="translated">Das Entfernen von Projekten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_projects_is_not_supported">
<source>Adding projects is not supported.</source>
<target state="translated">Das Hinzufügen von Projekten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution">
<source>Symbol's project could not be found in the provided solution</source>
<target state="translated">Das Projekt des Symbols wurde in der angegebenen Projektmappe nicht gefunden.</target>
<note />
</trans-unit>
<trans-unit id="Sync_namespace_to_folder_structure">
<source>Sync namespace to folder structure</source>
<target state="translated">Namespace mit Ordnerstruktur synchronisieren</target>
<note />
</trans-unit>
<trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed">
<source>The contents of a SourceGeneratedDocument may not be changed.</source>
<target state="translated">Der Inhalt eines SourceGeneratedDocument kann nicht geändert werden.</target>
<note>{locked:SourceGeneratedDocument}</note>
</trans-unit>
<trans-unit id="The_project_already_contains_the_specified_reference">
<source>The project already contains the specified reference.</source>
<target state="translated">Im Projekt ist der angegebene Verweis bereits enthalten.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_reference">
<source>The solution already contains the specified reference.</source>
<target state="translated">Der angegebene Verweis ist bereits in der Projektmappe enthalten.</target>
<note />
</trans-unit>
<trans-unit id="Unknown">
<source>Unknown</source>
<target state="translated">Unbekannt</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_files">
<source>Visual Basic files</source>
<target state="translated">Visual Basic-Dateien</target>
<note />
</trans-unit>
<trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access">
<source>Adding imports will bring an extension method into scope with the same name as '{0}'</source>
<target state="translated">Durch das Hinzufügen von Importen wird eine Erweiterungsmethode mit dem gleichen Namen wie "{0}" in den Bereich eingeführt.</target>
<note />
</trans-unit>
<trans-unit id="Workspace_error">
<source>Workspace error</source>
<target state="translated">Arbeitsbereichsfehler</target>
<note />
</trans-unit>
<trans-unit id="Workspace_is_not_empty">
<source>Workspace is not empty.</source>
<target state="translated">Arbeitsbereich ist nicht leer.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_in_a_different_project">
<source>{0} is in a different project.</source>
<target state="translated">"{0}" befindet sich in einem anderen Projekt.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_part_of_the_workspace">
<source>'{0}' is not part of the workspace.</source>
<target state="translated">"{0}" ist nicht Teil des Arbeitsbereichs.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_part_of_the_workspace">
<source>'{0}' is already part of the workspace.</source>
<target state="translated">"{0}" ist bereits Teil des Arbeitsbereichs.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_referenced">
<source>'{0}' is not referenced.</source>
<target state="translated">"{0}" ist nicht referenziert.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_referenced">
<source>'{0}' is already referenced.</source>
<target state="translated">"{0}" ist bereits referenziert.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference">
<source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source>
<target state="translated">Das Hinzufügen der Projektreferenz "{0}" zu "{1}" wird einen Zirkelbezug verursachen.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_not_referenced">
<source>Metadata is not referenced.</source>
<target state="translated">Metadaten sind nicht referenziert.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_already_referenced">
<source>Metadata is already referenced.</source>
<target state="translated">Metadaten sind bereits referenziert.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_present">
<source>{0} is not present.</source>
<target state="translated">{0} ist nicht vorhanden.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_present">
<source>{0} is already present.</source>
<target state="translated">{0} ist bereits vorhanden.</target>
<note />
</trans-unit>
<trans-unit id="The_specified_document_is_not_a_version_of_this_document">
<source>The specified document is not a version of this document.</source>
<target state="translated">Das angegebene Dokument ist keine Version dieses Dokuments.</target>
<note />
</trans-unit>
<trans-unit id="The_language_0_is_not_supported">
<source>The language '{0}' is not supported.</source>
<target state="translated">Die Sprache "{0}" wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_project">
<source>The solution already contains the specified project.</source>
<target state="translated">Die Lösung enthält bereits das angegebene Projekt.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_project">
<source>The solution does not contain the specified project.</source>
<target state="translated">Lösung enthält nicht das angegebene Projekt.</target>
<note />
</trans-unit>
<trans-unit id="The_project_already_references_the_target_project">
<source>The project already references the target project.</source>
<target state="translated">Das Projekt verweist bereits auf das Zielprojekt.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_document">
<source>The solution already contains the specified document.</source>
<target state="translated">Die Lösung enthält bereits das angegebene Dokument.</target>
<note />
</trans-unit>
<trans-unit id="Temporary_storage_cannot_be_written_more_than_once">
<source>Temporary storage cannot be written more than once.</source>
<target state="translated">Temporärer Speicher kann nicht mehr als einmal geschrieben werden.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_open">
<source>'{0}' is not open.</source>
<target state="translated">"{0}" ist nicht geöffnet.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Für diese Option kann kein Sprachenname angegeben werden.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Für diese Option muss ein Sprachenname angegeben werden.</target>
<note />
</trans-unit>
<trans-unit id="File_was_externally_modified_colon_0">
<source>File was externally modified: {0}.</source>
<target state="translated">Datei wurde extern modifiziert: {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unrecognized_language_name">
<source>Unrecognized language name.</source>
<target state="translated">Unerkannter Sprachenname.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_metadata_reference_colon_0">
<source>Can't resolve metadata reference: '{0}'.</source>
<target state="translated">Metadatenreferenz kann nicht aufgelöst werden: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_analyzer_reference_colon_0">
<source>Can't resolve analyzer reference: '{0}'.</source>
<target state="translated">Analysereferenz kann nicht aufgelöst werden: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_Project">
<source>Invalid project block, expected "=" after Project.</source>
<target state="translated">Ungültiger Projektblock, erwartet wird "=" nach Projekt.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_name">
<source>Invalid project block, expected "," after project name.</source>
<target state="translated">Ungültiger Projektblock, erwartet wird "," nach Projektname.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_path">
<source>Invalid project block, expected "," after project path.</source>
<target state="translated">Ungültiger Projektblock, erwartet wird "," nach Projektpfad.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0">
<source>Expected {0}.</source>
<target state="translated">Erwartet wird {0}.</target>
<note />
</trans-unit>
<trans-unit id="_0_must_be_a_non_null_and_non_empty_string">
<source>"{0}" must be a non-null and non-empty string.</source>
<target state="translated">"{0}" muss eine Zeichenfolge sein, die nicht null und nicht leer ist.</target>
<note />
</trans-unit>
<trans-unit id="Expected_header_colon_0">
<source>Expected header: "{0}".</source>
<target state="translated">Erwartete Überschrift: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Expected_end_of_file">
<source>Expected end-of-file.</source>
<target state="translated">Erwartetes Dateiende.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0_line">
<source>Expected {0} line.</source>
<target state="translated">Erwartete {0}-Zeile.</target>
<note />
</trans-unit>
<trans-unit id="This_submission_already_references_another_submission_project">
<source>This submission already references another submission project.</source>
<target state="translated">Diese Übermittlung verweist bereits auf ein anderes Übermittlungsprojekt.</target>
<note />
</trans-unit>
<trans-unit id="_0_still_contains_open_documents">
<source>{0} still contains open documents.</source>
<target state="translated">{0} enthält noch offene Dokumente.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_still_open">
<source>{0} is still open.</source>
<target state="translated">"{0}" ist noch geöffnet.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Arrays mit mehr als einer Dimension können nicht serialisiert werden.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Der Wert ist zu groß, um als ganze 30-Bit-Zahl ohne Vorzeichen dargestellt zu werden.</target>
<note />
</trans-unit>
<trans-unit id="Specified_path_must_be_absolute">
<source>Specified path must be absolute.</source>
<target state="translated">Angegebener Pfad muss absolut sein.</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified.</source>
<target state="translated">Der Name kann vereinfacht werden.</target>
<note />
</trans-unit>
<trans-unit id="Unknown_identifier">
<source>Unknown identifier.</source>
<target state="translated">Unbekannter Bezeichner.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_generate_code_for_unsupported_operator_0">
<source>Cannot generate code for unsupported operator '{0}'</source>
<target state="translated">Kann keinen Code für nicht unterstützten Operator "{0}" generieren</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_binary_operator">
<source>Invalid number of parameters for binary operator.</source>
<target state="translated">Ungültige Parameteranzahl für binären Operator.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_unary_operator">
<source>Invalid number of parameters for unary operator.</source>
<target state="translated">Ungültige Parameteranzahl für unären Operator.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language">
<source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source>
<target state="translated">Projekt "{0}" kann nicht geöffnet werden, da die Dateierweiterung "{1}" keiner Sprache zugeordnet ist.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported">
<source>Cannot open project '{0}' because the language '{1}' is not supported.</source>
<target state="translated">Projekt "{0}" kann nicht geöffnet werden, da die Sprache "{1}" nicht unterstützt wird.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_file_path_colon_0">
<source>Invalid project file path: '{0}'</source>
<target state="translated">Ungültiger Projektdateipfad: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Invalid_solution_file_path_colon_0">
<source>Invalid solution file path: '{0}'</source>
<target state="translated">Ungültiger Lösungsdateipfad: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Project_file_not_found_colon_0">
<source>Project file not found: '{0}'</source>
<target state="translated">Projektdatei nicht gefunden: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Solution_file_not_found_colon_0">
<source>Solution file not found: '{0}'</source>
<target state="translated">Lösungsdatei nicht gefunden: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Unmerged_change_from_project_0">
<source>Unmerged change from project '{0}'</source>
<target state="translated">Nicht gemergte Änderung aus Projekt "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Added_colon">
<source>Added:</source>
<target state="translated">Hinzugefügt:</target>
<note />
</trans-unit>
<trans-unit id="After_colon">
<source>After:</source>
<target state="translated">Nach:</target>
<note />
</trans-unit>
<trans-unit id="Before_colon">
<source>Before:</source>
<target state="translated">Vor:</target>
<note />
</trans-unit>
<trans-unit id="Removed_colon">
<source>Removed:</source>
<target state="translated">Entfernt:</target>
<note />
</trans-unit>
<trans-unit id="Invalid_CodePage_value_colon_0">
<source>Invalid CodePage value: {0}</source>
<target state="translated">Ungültiger CodePage-Wert: {0}</target>
<note />
</trans-unit>
<trans-unit id="Adding_additional_documents_is_not_supported">
<source>Adding additional documents is not supported.</source>
<target state="translated">Das Hinzufügen weitere Dokumente wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_references_is_not_supported">
<source>Adding analyzer references is not supported.</source>
<target state="translated">Das Hinzufügen von Verweisen der Analyse wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_documents_is_not_supported">
<source>Adding documents is not supported.</source>
<target state="translated">Das Hinzufügen von Dokumenten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_metadata_references_is_not_supported">
<source>Adding metadata references is not supported.</source>
<target state="translated">Das Hinzufügen von Verweisen auf Metadaten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_references_is_not_supported">
<source>Adding project references is not supported.</source>
<target state="translated">Das Hinzufügen von Projektverweisen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_additional_documents_is_not_supported">
<source>Changing additional documents is not supported.</source>
<target state="translated">Das Ändern weiterer Dokumente wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_documents_is_not_supported">
<source>Changing documents is not supported.</source>
<target state="translated">Das Ändern von Dokumenten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_project_properties_is_not_supported">
<source>Changing project properties is not supported.</source>
<target state="translated">Das Ändern von Projekteigenschaften wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_additional_documents_is_not_supported">
<source>Removing additional documents is not supported.</source>
<target state="translated">Das Entfernen weiterer Dokumente wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_references_is_not_supported">
<source>Removing analyzer references is not supported.</source>
<target state="translated">Das Entfernen von Verweisen der Analyse wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_documents_is_not_supported">
<source>Removing documents is not supported.</source>
<target state="translated">Das Entfernen von Dokumenten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_metadata_references_is_not_supported">
<source>Removing metadata references is not supported.</source>
<target state="translated">Das Entfernen von Verweisen auf Metadaten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_project_references_is_not_supported">
<source>Removing project references is not supported.</source>
<target state="translated">Das Entfernen von Projektverweisen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace">
<source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source>
<target state="translated">Ein Dienst vom Typ "{0}" ist zum Ausführen der Aufgabe erforderlich, steht aber im Arbeitsbereich nicht zur Verfügung.</target>
<note />
</trans-unit>
<trans-unit id="At_least_one_diagnostic_must_be_supplied">
<source>At least one diagnostic must be supplied.</source>
<target state="translated">Es muss mindestens eine Diagnose bereitgestellt sein.</target>
<note />
</trans-unit>
<trans-unit id="Diagnostic_must_have_span_0">
<source>Diagnostic must have span '{0}'</source>
<target state="translated">Diagnose muss den Bereich "{0}" enthalten</target>
<note />
</trans-unit>
<trans-unit id="Cannot_deserialize_type_0">
<source>Cannot deserialize type '{0}'.</source>
<target state="translated">Typ "{0}" kann nicht deserialisiert werden.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Typ "{0}" kann nicht serialisiert werden.</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Der Typ "{0}" wird vom Serialisierungsbinder nicht verstanden.</target>
<note />
</trans-unit>
<trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1">
<source>Label for node '{0}' is invalid, it must be within [0, {1}).</source>
<target state="translated">Die Bezeichnung für Knoten '{0}' ist ungültig, sie muss innerhalb von [0, {1}) liegen.</target>
<note />
</trans-unit>
<trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label">
<source>Matching nodes '{0}' and '{1}' must have the same label.</source>
<target state="translated">Die übereinstimmenden Knoten '{0}' und '{1}' müssen dieselbe Bezeichnung aufweisen.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_new_tree">
<source>Node '{0}' must be contained in the new tree.</source>
<target state="translated">Der Knoten '{0}' muss im neuen Baum enthalten sein.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_old_tree">
<source>Node '{0}' must be contained in the old tree.</source>
<target state="translated">Der Knoten '{0}' muss im alten Baum enthalten sein.</target>
<note />
</trans-unit>
<trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol">
<source>The member '{0}' is not declared within the declaration of the symbol.</source>
<target state="translated">Der Member '{0}' wird nicht innerhalb der Deklaration des Symbols deklariert.</target>
<note />
</trans-unit>
<trans-unit id="The_position_is_not_within_the_symbol_s_declaration">
<source>The position is not within the symbol's declaration</source>
<target state="translated">Die Position liegt nicht innerhalb der Deklaration des Symbols.</target>
<note />
</trans-unit>
<trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution">
<source>The symbol '{0}' cannot be located within the current solution.</source>
<target state="translated">Das Symbol '{0}' kann nicht in die aktuelle Projektmappe geladen werden.</target>
<note />
</trans-unit>
<trans-unit id="Changing_compilation_options_is_not_supported">
<source>Changing compilation options is not supported.</source>
<target state="translated">Das Ändern von Kompilierungsoptionen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_parse_options_is_not_supported">
<source>Changing parse options is not supported.</source>
<target state="translated">Das Ändern von Analyseoptionen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="The_node_is_not_part_of_the_tree">
<source>The node is not part of the tree.</source>
<target state="translated">Dieser Knoten ist nicht Teil des Baums.</target>
<note />
</trans-unit>
<trans-unit id="This_workspace_does_not_support_opening_and_closing_documents">
<source>This workspace does not support opening and closing documents.</source>
<target state="translated">Das Öffnen und Schließen von Dokumenten wird in diesem Arbeitsbereich nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Exceptions_colon">
<source>Exceptions:</source>
<target state="translated">Ausnahmen:</target>
<note />
</trans-unit>
<trans-unit id="_0_returned_an_uninitialized_ImmutableArray">
<source>'{0}' returned an uninitialized ImmutableArray</source>
<target state="translated">"{0}" hat ein nicht initialisiertes "ImmutableArray" zurückgegeben.</target>
<note />
</trans-unit>
<trans-unit id="Failure">
<source>Failure</source>
<target state="translated">Fehler</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Warnung</target>
<note />
</trans-unit>
<trans-unit id="Enable">
<source>Enable</source>
<target state="translated">Aktivieren</target>
<note />
</trans-unit>
<trans-unit id="Enable_and_ignore_future_errors">
<source>Enable and ignore future errors</source>
<target state="translated">Aktivieren und weitere Fehler ignorieren</target>
<note />
</trans-unit>
<trans-unit id="_0_encountered_an_error_and_has_been_disabled">
<source>'{0}' encountered an error and has been disabled.</source>
<target state="translated">"{0}" hat einen Fehler festgestellt und wurde deaktiviert.</target>
<note />
</trans-unit>
<trans-unit id="Show_Stack_Trace">
<source>Show Stack Trace</source>
<target state="translated">Stapelüberwachung anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Der Datenstrom ist zu lang.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Der Deserialisierungsreader für "{0}" hat eine falsche Anzahl von Werten gelesen.</target>
<note />
</trans-unit>
<trans-unit id="Async_Method">
<source>Async Method</source>
<target state="translated">Asynchrone Methode</target>
<note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note>
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Fehler</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">NONE</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Vorschlag</target>
<note />
</trans-unit>
<trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2">
<source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source>
<target state="translated">Die Größe der Datei "{0}" beträgt {1} und überschreitet so die maximal zulässige Größe von {2}.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_property_is_not_supported">
<source>Changing document properties is not supported</source>
<target state="translated">Das Ändern der Dokumenteigenschaften wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="dot_NET_Coding_Conventions">
<source>.NET Coding Conventions</source>
<target state="translated">.NET-Codierungskonventionen</target>
<note />
</trans-unit>
<trans-unit id="Variables_captured_colon">
<source>Variables captured:</source>
<target state="translated">Erfasste Variablen:</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | <?xml version="1.0" encoding="utf-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd">
<file datatype="xml" source-language="en" target-language="de" original="../WorkspacesResources.resx">
<body>
<trans-unit id="A_project_may_not_reference_itself">
<source>A project may not reference itself.</source>
<target state="translated">Ein Projekt darf nicht auf sich selbst verweisen.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_config_documents_is_not_supported">
<source>Adding analyzer config documents is not supported.</source>
<target state="translated">Das Hinzufügen von Konfigurationsdokumenten des Analysetools wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="An_error_occurred_while_reading_the_specified_configuration_file_colon_0">
<source>An error occurred while reading the specified configuration file: {0}</source>
<target state="translated">Beim Lesen der angegebenen Konfigurationsdatei ist ein Fehler aufgetreten: {0}</target>
<note />
</trans-unit>
<trans-unit id="CSharp_files">
<source>C# files</source>
<target state="translated">C#-Dateien</target>
<note />
</trans-unit>
<trans-unit id="Cannot_apply_action_that_is_not_in_0">
<source>Cannot apply action that is not in '{0}'</source>
<target state="translated">Es können nur in "{0}" enthaltene Aktionen angewendet werden.</target>
<note />
</trans-unit>
<trans-unit id="Changing_analyzer_config_documents_is_not_supported">
<source>Changing analyzer config documents is not supported.</source>
<target state="translated">Das Ändern von Konfigurationsdokumenten des Analysetools wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_0_is_not_supported">
<source>Changing document '{0}' is not supported.</source>
<target state="translated">Das Ändern des Dokuments "{0}" wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="CodeAction_{0}_did_not_produce_a_changed_solution">
<source>CodeAction '{0}' did not produce a changed solution</source>
<target state="translated">Durch CodeAction "{0}" wurde keine geänderte Lösung erstellt.</target>
<note>"CodeAction" is a specific type, and {0} represents the title shown by the action.</note>
</trans-unit>
<trans-unit id="Core_EditorConfig_Options">
<source>Core EditorConfig Options</source>
<target state="translated">Wichtige EditorConfig-Optionen</target>
<note />
</trans-unit>
<trans-unit id="DateTimeKind_must_be_Utc">
<source>DateTimeKind must be Utc</source>
<target state="translated">"DateTimeKind" muss UTC sein.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_2_or_3_but_given_one_is_4">
<source>Destination type must be a {0}, {1}, {2} or {3}, but given one is {4}.</source>
<target state="translated">Der Zieltyp muss "{0}", "{1}", "{2}" oder "{3}" lauten. Es wurde jedoch "{4}" angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Document_does_not_support_syntax_trees">
<source>Document does not support syntax trees</source>
<target state="translated">Das Dokument unterstützt keine Syntaxstrukturen.</target>
<note />
</trans-unit>
<trans-unit id="Error_reading_content_of_source_file_0_1">
<source>Error reading content of source file '{0}' -- '{1}'.</source>
<target state="translated">Fehler beim Lesen des Inhalts der Quelldatei "{0}": "{1}".</target>
<note />
</trans-unit>
<trans-unit id="Indentation_and_spacing">
<source>Indentation and spacing</source>
<target state="translated">Einzüge und Abstände</target>
<note />
</trans-unit>
<trans-unit id="New_line_preferences">
<source>New line preferences</source>
<target state="translated">Einstellungen für neue Zeilen</target>
<note />
</trans-unit>
<trans-unit id="Only_submission_project_can_reference_submission_projects">
<source>Only submission project can reference submission projects.</source>
<target state="translated">Nur ein Übermittlungsprojekt kann auf Übermittlungsprojekte verweisen.</target>
<note />
</trans-unit>
<trans-unit id="Options_did_not_come_from_specified_Solution">
<source>Options did not come from specified Solution</source>
<target state="translated">Optionen stammen nicht aus der angegebenen Projektmappe.</target>
<note />
</trans-unit>
<trans-unit id="Predefined_conversion_from_0_to_1">
<source>Predefined conversion from {0} to {1}.</source>
<target state="translated">Vordefinierte Konvertierung von "{0}" in "{1}".</target>
<note />
</trans-unit>
<trans-unit id="Project_does_not_contain_specified_reference">
<source>Project does not contain specified reference</source>
<target state="translated">Der angegebene Verweis ist im Projekt nicht enthalten.</target>
<note />
</trans-unit>
<trans-unit id="Refactoring_Only">
<source>Refactoring Only</source>
<target state="translated">Nur Refactoring</target>
<note />
</trans-unit>
<trans-unit id="Remove_the_line_below_if_you_want_to_inherit_dot_editorconfig_settings_from_higher_directories">
<source>Remove the line below if you want to inherit .editorconfig settings from higher directories</source>
<target state="translated">Entfernen Sie die folgende Zeile, wenn Sie EDITORCONFIG-Einstellungen von höheren Verzeichnissen vererben möchten.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_config_documents_is_not_supported">
<source>Removing analyzer config documents is not supported.</source>
<target state="translated">Das Entfernen von Konfigurationsdokumenten des Analysetools wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Rename_0_to_1">
<source>Rename '{0}' to '{1}'</source>
<target state="translated">"{0}" in "{1}" umbenennen</target>
<note />
</trans-unit>
<trans-unit id="Solution_does_not_contain_specified_reference">
<source>Solution does not contain specified reference</source>
<target state="translated">Der angegebene Verweis ist nicht in der Projektmappe enthalten.</target>
<note />
</trans-unit>
<trans-unit id="Symbol_0_is_not_from_source">
<source>Symbol "{0}" is not from source.</source>
<target state="translated">Symbol "{0}" ist nicht aus Quelle.</target>
<note />
</trans-unit>
<trans-unit id="Documentation_comment_id_must_start_with_E_F_M_N_P_or_T">
<source>Documentation comment id must start with E, F, M, N, P or T</source>
<target state="translated">Dokumentationskommentar-ID muss mit E, F, M, N, P oder T beginnen</target>
<note />
</trans-unit>
<trans-unit id="Cycle_detected_in_extensions">
<source>Cycle detected in extensions</source>
<target state="translated">Zyklus in Erweiterungen entdeckt</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_but_given_one_is_1">
<source>Destination type must be a {0}, but given one is {1}.</source>
<target state="translated">Zieltyp muss {0} sein. Es wurde jedoch {1} angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_or_a_1_but_given_one_is_2">
<source>Destination type must be a {0} or a {1}, but given one is {2}.</source>
<target state="translated">Zieltyp muss {0} oder {1} sein. Es wurde jedoch {2} angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Destination_type_must_be_a_0_1_or_2_but_given_one_is_3">
<source>Destination type must be a {0}, {1} or {2}, but given one is {3}.</source>
<target state="translated">Zieltyp muss {0}, {1} oder {2} sein. Es wurde jedoch {3} angegeben.</target>
<note />
</trans-unit>
<trans-unit id="Could_not_find_location_to_generation_symbol_into">
<source>Could not find location to generation symbol into.</source>
<target state="translated">Konnte keinen Ort finden, in den das Symbol generiert werden kann.</target>
<note />
</trans-unit>
<trans-unit id="No_location_provided_to_add_statements_to">
<source>No location provided to add statements to.</source>
<target state="translated">Kein Ort angegeben, zu dem Anweisungen hinzugefügt werden.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_not_in_source">
<source>Destination location was not in source.</source>
<target state="translated">Zielort war nicht in Quelle.</target>
<note />
</trans-unit>
<trans-unit id="Destination_location_was_from_a_different_tree">
<source>Destination location was from a different tree.</source>
<target state="translated">Zielort stammt aus anderem Baum.</target>
<note />
</trans-unit>
<trans-unit id="Node_is_of_the_wrong_type">
<source>Node is of the wrong type.</source>
<target state="translated">Knoten hat den falschen Typ.</target>
<note />
</trans-unit>
<trans-unit id="Location_must_be_null_or_from_source">
<source>Location must be null or from source.</source>
<target state="translated">Ort muss null oder von Quelle sein.</target>
<note />
</trans-unit>
<trans-unit id="Duplicate_source_file_0_in_project_1">
<source>Duplicate source file '{0}' in project '{1}'</source>
<target state="translated">Doppelte Quelldatei "{0}" in Projekt "{1}"</target>
<note />
</trans-unit>
<trans-unit id="Removing_projects_is_not_supported">
<source>Removing projects is not supported.</source>
<target state="translated">Das Entfernen von Projekten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_projects_is_not_supported">
<source>Adding projects is not supported.</source>
<target state="translated">Das Hinzufügen von Projekten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Symbols_project_could_not_be_found_in_the_provided_solution">
<source>Symbol's project could not be found in the provided solution</source>
<target state="translated">Das Projekt des Symbols wurde in der angegebenen Projektmappe nicht gefunden.</target>
<note />
</trans-unit>
<trans-unit id="Sync_namespace_to_folder_structure">
<source>Sync namespace to folder structure</source>
<target state="translated">Namespace mit Ordnerstruktur synchronisieren</target>
<note />
</trans-unit>
<trans-unit id="The_contents_of_a_SourceGeneratedDocument_may_not_be_changed">
<source>The contents of a SourceGeneratedDocument may not be changed.</source>
<target state="translated">Der Inhalt eines SourceGeneratedDocument kann nicht geändert werden.</target>
<note>{locked:SourceGeneratedDocument}</note>
</trans-unit>
<trans-unit id="The_project_already_contains_the_specified_reference">
<source>The project already contains the specified reference.</source>
<target state="translated">Im Projekt ist der angegebene Verweis bereits enthalten.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_reference">
<source>The solution already contains the specified reference.</source>
<target state="translated">Der angegebene Verweis ist bereits in der Projektmappe enthalten.</target>
<note />
</trans-unit>
<trans-unit id="Unknown">
<source>Unknown</source>
<target state="translated">Unbekannt</target>
<note />
</trans-unit>
<trans-unit id="Visual_Basic_files">
<source>Visual Basic files</source>
<target state="translated">Visual Basic-Dateien</target>
<note />
</trans-unit>
<trans-unit id="Warning_adding_imports_will_bring_an_extension_method_into_scope_with_the_same_name_as_member_access">
<source>Adding imports will bring an extension method into scope with the same name as '{0}'</source>
<target state="translated">Durch das Hinzufügen von Importen wird eine Erweiterungsmethode mit dem gleichen Namen wie "{0}" in den Bereich eingeführt.</target>
<note />
</trans-unit>
<trans-unit id="Workspace_error">
<source>Workspace error</source>
<target state="translated">Arbeitsbereichsfehler</target>
<note />
</trans-unit>
<trans-unit id="Workspace_is_not_empty">
<source>Workspace is not empty.</source>
<target state="translated">Arbeitsbereich ist nicht leer.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_in_a_different_project">
<source>{0} is in a different project.</source>
<target state="translated">"{0}" befindet sich in einem anderen Projekt.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_part_of_the_workspace">
<source>'{0}' is not part of the workspace.</source>
<target state="translated">"{0}" ist nicht Teil des Arbeitsbereichs.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_part_of_the_workspace">
<source>'{0}' is already part of the workspace.</source>
<target state="translated">"{0}" ist bereits Teil des Arbeitsbereichs.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_referenced">
<source>'{0}' is not referenced.</source>
<target state="translated">"{0}" ist nicht referenziert.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_referenced">
<source>'{0}' is already referenced.</source>
<target state="translated">"{0}" ist bereits referenziert.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_reference_from_0_to_1_will_cause_a_circular_reference">
<source>Adding project reference from '{0}' to '{1}' will cause a circular reference.</source>
<target state="translated">Das Hinzufügen der Projektreferenz "{0}" zu "{1}" wird einen Zirkelbezug verursachen.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_not_referenced">
<source>Metadata is not referenced.</source>
<target state="translated">Metadaten sind nicht referenziert.</target>
<note />
</trans-unit>
<trans-unit id="Metadata_is_already_referenced">
<source>Metadata is already referenced.</source>
<target state="translated">Metadaten sind bereits referenziert.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_present">
<source>{0} is not present.</source>
<target state="translated">{0} ist nicht vorhanden.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_already_present">
<source>{0} is already present.</source>
<target state="translated">{0} ist bereits vorhanden.</target>
<note />
</trans-unit>
<trans-unit id="The_specified_document_is_not_a_version_of_this_document">
<source>The specified document is not a version of this document.</source>
<target state="translated">Das angegebene Dokument ist keine Version dieses Dokuments.</target>
<note />
</trans-unit>
<trans-unit id="The_language_0_is_not_supported">
<source>The language '{0}' is not supported.</source>
<target state="translated">Die Sprache "{0}" wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_project">
<source>The solution already contains the specified project.</source>
<target state="translated">Die Lösung enthält bereits das angegebene Projekt.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_does_not_contain_the_specified_project">
<source>The solution does not contain the specified project.</source>
<target state="translated">Lösung enthält nicht das angegebene Projekt.</target>
<note />
</trans-unit>
<trans-unit id="The_project_already_references_the_target_project">
<source>The project already references the target project.</source>
<target state="translated">Das Projekt verweist bereits auf das Zielprojekt.</target>
<note />
</trans-unit>
<trans-unit id="The_solution_already_contains_the_specified_document">
<source>The solution already contains the specified document.</source>
<target state="translated">Die Lösung enthält bereits das angegebene Dokument.</target>
<note />
</trans-unit>
<trans-unit id="Temporary_storage_cannot_be_written_more_than_once">
<source>Temporary storage cannot be written more than once.</source>
<target state="translated">Temporärer Speicher kann nicht mehr als einmal geschrieben werden.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_not_open">
<source>'{0}' is not open.</source>
<target state="translated">"{0}" ist nicht geöffnet.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_cannot_be_specified_for_this_option">
<source>A language name cannot be specified for this option.</source>
<target state="translated">Für diese Option kann kein Sprachenname angegeben werden.</target>
<note />
</trans-unit>
<trans-unit id="A_language_name_must_be_specified_for_this_option">
<source>A language name must be specified for this option.</source>
<target state="translated">Für diese Option muss ein Sprachenname angegeben werden.</target>
<note />
</trans-unit>
<trans-unit id="File_was_externally_modified_colon_0">
<source>File was externally modified: {0}.</source>
<target state="translated">Datei wurde extern modifiziert: {0}.</target>
<note />
</trans-unit>
<trans-unit id="Unrecognized_language_name">
<source>Unrecognized language name.</source>
<target state="translated">Unerkannter Sprachenname.</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_metadata_reference_colon_0">
<source>Can't resolve metadata reference: '{0}'.</source>
<target state="translated">Metadatenreferenz kann nicht aufgelöst werden: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Can_t_resolve_analyzer_reference_colon_0">
<source>Can't resolve analyzer reference: '{0}'.</source>
<target state="translated">Analysereferenz kann nicht aufgelöst werden: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_Project">
<source>Invalid project block, expected "=" after Project.</source>
<target state="translated">Ungültiger Projektblock, erwartet wird "=" nach Projekt.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_name">
<source>Invalid project block, expected "," after project name.</source>
<target state="translated">Ungültiger Projektblock, erwartet wird "," nach Projektname.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_block_expected_after_project_path">
<source>Invalid project block, expected "," after project path.</source>
<target state="translated">Ungültiger Projektblock, erwartet wird "," nach Projektpfad.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0">
<source>Expected {0}.</source>
<target state="translated">Erwartet wird {0}.</target>
<note />
</trans-unit>
<trans-unit id="_0_must_be_a_non_null_and_non_empty_string">
<source>"{0}" must be a non-null and non-empty string.</source>
<target state="translated">"{0}" muss eine Zeichenfolge sein, die nicht null und nicht leer ist.</target>
<note />
</trans-unit>
<trans-unit id="Expected_header_colon_0">
<source>Expected header: "{0}".</source>
<target state="translated">Erwartete Überschrift: "{0}".</target>
<note />
</trans-unit>
<trans-unit id="Expected_end_of_file">
<source>Expected end-of-file.</source>
<target state="translated">Erwartetes Dateiende.</target>
<note />
</trans-unit>
<trans-unit id="Expected_0_line">
<source>Expected {0} line.</source>
<target state="translated">Erwartete {0}-Zeile.</target>
<note />
</trans-unit>
<trans-unit id="This_submission_already_references_another_submission_project">
<source>This submission already references another submission project.</source>
<target state="translated">Diese Übermittlung verweist bereits auf ein anderes Übermittlungsprojekt.</target>
<note />
</trans-unit>
<trans-unit id="_0_still_contains_open_documents">
<source>{0} still contains open documents.</source>
<target state="translated">{0} enthält noch offene Dokumente.</target>
<note />
</trans-unit>
<trans-unit id="_0_is_still_open">
<source>{0} is still open.</source>
<target state="translated">"{0}" ist noch geöffnet.</target>
<note />
</trans-unit>
<trans-unit id="Arrays_with_more_than_one_dimension_cannot_be_serialized">
<source>Arrays with more than one dimension cannot be serialized.</source>
<target state="translated">Arrays mit mehr als einer Dimension können nicht serialisiert werden.</target>
<note />
</trans-unit>
<trans-unit id="Value_too_large_to_be_represented_as_a_30_bit_unsigned_integer">
<source>Value too large to be represented as a 30 bit unsigned integer.</source>
<target state="translated">Der Wert ist zu groß, um als ganze 30-Bit-Zahl ohne Vorzeichen dargestellt zu werden.</target>
<note />
</trans-unit>
<trans-unit id="Specified_path_must_be_absolute">
<source>Specified path must be absolute.</source>
<target state="translated">Angegebener Pfad muss absolut sein.</target>
<note />
</trans-unit>
<trans-unit id="Name_can_be_simplified">
<source>Name can be simplified.</source>
<target state="translated">Der Name kann vereinfacht werden.</target>
<note />
</trans-unit>
<trans-unit id="Unknown_identifier">
<source>Unknown identifier.</source>
<target state="translated">Unbekannter Bezeichner.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_generate_code_for_unsupported_operator_0">
<source>Cannot generate code for unsupported operator '{0}'</source>
<target state="translated">Kann keinen Code für nicht unterstützten Operator "{0}" generieren</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_binary_operator">
<source>Invalid number of parameters for binary operator.</source>
<target state="translated">Ungültige Parameteranzahl für binären Operator.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_number_of_parameters_for_unary_operator">
<source>Invalid number of parameters for unary operator.</source>
<target state="translated">Ungültige Parameteranzahl für unären Operator.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_file_extension_1_is_not_associated_with_a_language">
<source>Cannot open project '{0}' because the file extension '{1}' is not associated with a language.</source>
<target state="translated">Projekt "{0}" kann nicht geöffnet werden, da die Dateierweiterung "{1}" keiner Sprache zugeordnet ist.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_open_project_0_because_the_language_1_is_not_supported">
<source>Cannot open project '{0}' because the language '{1}' is not supported.</source>
<target state="translated">Projekt "{0}" kann nicht geöffnet werden, da die Sprache "{1}" nicht unterstützt wird.</target>
<note />
</trans-unit>
<trans-unit id="Invalid_project_file_path_colon_0">
<source>Invalid project file path: '{0}'</source>
<target state="translated">Ungültiger Projektdateipfad: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Invalid_solution_file_path_colon_0">
<source>Invalid solution file path: '{0}'</source>
<target state="translated">Ungültiger Lösungsdateipfad: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Project_file_not_found_colon_0">
<source>Project file not found: '{0}'</source>
<target state="translated">Projektdatei nicht gefunden: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Solution_file_not_found_colon_0">
<source>Solution file not found: '{0}'</source>
<target state="translated">Lösungsdatei nicht gefunden: "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Unmerged_change_from_project_0">
<source>Unmerged change from project '{0}'</source>
<target state="translated">Nicht gemergte Änderung aus Projekt "{0}"</target>
<note />
</trans-unit>
<trans-unit id="Added_colon">
<source>Added:</source>
<target state="translated">Hinzugefügt:</target>
<note />
</trans-unit>
<trans-unit id="After_colon">
<source>After:</source>
<target state="translated">Nach:</target>
<note />
</trans-unit>
<trans-unit id="Before_colon">
<source>Before:</source>
<target state="translated">Vor:</target>
<note />
</trans-unit>
<trans-unit id="Removed_colon">
<source>Removed:</source>
<target state="translated">Entfernt:</target>
<note />
</trans-unit>
<trans-unit id="Invalid_CodePage_value_colon_0">
<source>Invalid CodePage value: {0}</source>
<target state="translated">Ungültiger CodePage-Wert: {0}</target>
<note />
</trans-unit>
<trans-unit id="Adding_additional_documents_is_not_supported">
<source>Adding additional documents is not supported.</source>
<target state="translated">Das Hinzufügen weitere Dokumente wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_analyzer_references_is_not_supported">
<source>Adding analyzer references is not supported.</source>
<target state="translated">Das Hinzufügen von Verweisen der Analyse wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_documents_is_not_supported">
<source>Adding documents is not supported.</source>
<target state="translated">Das Hinzufügen von Dokumenten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_metadata_references_is_not_supported">
<source>Adding metadata references is not supported.</source>
<target state="translated">Das Hinzufügen von Verweisen auf Metadaten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Adding_project_references_is_not_supported">
<source>Adding project references is not supported.</source>
<target state="translated">Das Hinzufügen von Projektverweisen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_additional_documents_is_not_supported">
<source>Changing additional documents is not supported.</source>
<target state="translated">Das Ändern weiterer Dokumente wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_documents_is_not_supported">
<source>Changing documents is not supported.</source>
<target state="translated">Das Ändern von Dokumenten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_project_properties_is_not_supported">
<source>Changing project properties is not supported.</source>
<target state="translated">Das Ändern von Projekteigenschaften wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_additional_documents_is_not_supported">
<source>Removing additional documents is not supported.</source>
<target state="translated">Das Entfernen weiterer Dokumente wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_analyzer_references_is_not_supported">
<source>Removing analyzer references is not supported.</source>
<target state="translated">Das Entfernen von Verweisen der Analyse wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_documents_is_not_supported">
<source>Removing documents is not supported.</source>
<target state="translated">Das Entfernen von Dokumenten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_metadata_references_is_not_supported">
<source>Removing metadata references is not supported.</source>
<target state="translated">Das Entfernen von Verweisen auf Metadaten wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Removing_project_references_is_not_supported">
<source>Removing project references is not supported.</source>
<target state="translated">Das Entfernen von Projektverweisen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Service_of_type_0_is_required_to_accomplish_the_task_but_is_not_available_from_the_workspace">
<source>Service of type '{0}' is required to accomplish the task but is not available from the workspace.</source>
<target state="translated">Ein Dienst vom Typ "{0}" ist zum Ausführen der Aufgabe erforderlich, steht aber im Arbeitsbereich nicht zur Verfügung.</target>
<note />
</trans-unit>
<trans-unit id="At_least_one_diagnostic_must_be_supplied">
<source>At least one diagnostic must be supplied.</source>
<target state="translated">Es muss mindestens eine Diagnose bereitgestellt sein.</target>
<note />
</trans-unit>
<trans-unit id="Diagnostic_must_have_span_0">
<source>Diagnostic must have span '{0}'</source>
<target state="translated">Diagnose muss den Bereich "{0}" enthalten</target>
<note />
</trans-unit>
<trans-unit id="Cannot_deserialize_type_0">
<source>Cannot deserialize type '{0}'.</source>
<target state="translated">Typ "{0}" kann nicht deserialisiert werden.</target>
<note />
</trans-unit>
<trans-unit id="Cannot_serialize_type_0">
<source>Cannot serialize type '{0}'.</source>
<target state="translated">Typ "{0}" kann nicht serialisiert werden.</target>
<note />
</trans-unit>
<trans-unit id="The_type_0_is_not_understood_by_the_serialization_binder">
<source>The type '{0}' is not understood by the serialization binder.</source>
<target state="translated">Der Typ "{0}" wird vom Serialisierungsbinder nicht verstanden.</target>
<note />
</trans-unit>
<trans-unit id="Label_for_node_0_is_invalid_it_must_be_within_bracket_0_1">
<source>Label for node '{0}' is invalid, it must be within [0, {1}).</source>
<target state="translated">Die Bezeichnung für Knoten '{0}' ist ungültig, sie muss innerhalb von [0, {1}) liegen.</target>
<note />
</trans-unit>
<trans-unit id="Matching_nodes_0_and_1_must_have_the_same_label">
<source>Matching nodes '{0}' and '{1}' must have the same label.</source>
<target state="translated">Die übereinstimmenden Knoten '{0}' und '{1}' müssen dieselbe Bezeichnung aufweisen.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_new_tree">
<source>Node '{0}' must be contained in the new tree.</source>
<target state="translated">Der Knoten '{0}' muss im neuen Baum enthalten sein.</target>
<note />
</trans-unit>
<trans-unit id="Node_0_must_be_contained_in_the_old_tree">
<source>Node '{0}' must be contained in the old tree.</source>
<target state="translated">Der Knoten '{0}' muss im alten Baum enthalten sein.</target>
<note />
</trans-unit>
<trans-unit id="The_member_0_is_not_declared_within_the_declaration_of_the_symbol">
<source>The member '{0}' is not declared within the declaration of the symbol.</source>
<target state="translated">Der Member '{0}' wird nicht innerhalb der Deklaration des Symbols deklariert.</target>
<note />
</trans-unit>
<trans-unit id="The_position_is_not_within_the_symbol_s_declaration">
<source>The position is not within the symbol's declaration</source>
<target state="translated">Die Position liegt nicht innerhalb der Deklaration des Symbols.</target>
<note />
</trans-unit>
<trans-unit id="The_symbol_0_cannot_be_located_within_the_current_solution">
<source>The symbol '{0}' cannot be located within the current solution.</source>
<target state="translated">Das Symbol '{0}' kann nicht in die aktuelle Projektmappe geladen werden.</target>
<note />
</trans-unit>
<trans-unit id="Changing_compilation_options_is_not_supported">
<source>Changing compilation options is not supported.</source>
<target state="translated">Das Ändern von Kompilierungsoptionen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Changing_parse_options_is_not_supported">
<source>Changing parse options is not supported.</source>
<target state="translated">Das Ändern von Analyseoptionen wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="The_node_is_not_part_of_the_tree">
<source>The node is not part of the tree.</source>
<target state="translated">Dieser Knoten ist nicht Teil des Baums.</target>
<note />
</trans-unit>
<trans-unit id="This_workspace_does_not_support_opening_and_closing_documents">
<source>This workspace does not support opening and closing documents.</source>
<target state="translated">Das Öffnen und Schließen von Dokumenten wird in diesem Arbeitsbereich nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="Exceptions_colon">
<source>Exceptions:</source>
<target state="translated">Ausnahmen:</target>
<note />
</trans-unit>
<trans-unit id="_0_returned_an_uninitialized_ImmutableArray">
<source>'{0}' returned an uninitialized ImmutableArray</source>
<target state="translated">"{0}" hat ein nicht initialisiertes "ImmutableArray" zurückgegeben.</target>
<note />
</trans-unit>
<trans-unit id="Failure">
<source>Failure</source>
<target state="translated">Fehler</target>
<note />
</trans-unit>
<trans-unit id="Warning">
<source>Warning</source>
<target state="translated">Warnung</target>
<note />
</trans-unit>
<trans-unit id="Enable">
<source>Enable</source>
<target state="translated">Aktivieren</target>
<note />
</trans-unit>
<trans-unit id="Enable_and_ignore_future_errors">
<source>Enable and ignore future errors</source>
<target state="translated">Aktivieren und weitere Fehler ignorieren</target>
<note />
</trans-unit>
<trans-unit id="_0_encountered_an_error_and_has_been_disabled">
<source>'{0}' encountered an error and has been disabled.</source>
<target state="translated">"{0}" hat einen Fehler festgestellt und wurde deaktiviert.</target>
<note />
</trans-unit>
<trans-unit id="Show_Stack_Trace">
<source>Show Stack Trace</source>
<target state="translated">Stapelüberwachung anzeigen</target>
<note />
</trans-unit>
<trans-unit id="Stream_is_too_long">
<source>Stream is too long.</source>
<target state="translated">Der Datenstrom ist zu lang.</target>
<note />
</trans-unit>
<trans-unit id="Deserialization_reader_for_0_read_incorrect_number_of_values">
<source>Deserialization reader for '{0}' read incorrect number of values.</source>
<target state="translated">Der Deserialisierungsreader für "{0}" hat eine falsche Anzahl von Werten gelesen.</target>
<note />
</trans-unit>
<trans-unit id="Async_Method">
<source>Async Method</source>
<target state="translated">Asynchrone Methode</target>
<note>{locked: async}{locked: method} These are keywords (unless the order of words or capitalization should be handled differently)</note>
</trans-unit>
<trans-unit id="Error">
<source>Error</source>
<target state="translated">Fehler</target>
<note />
</trans-unit>
<trans-unit id="None">
<source>None</source>
<target state="translated">NONE</target>
<note />
</trans-unit>
<trans-unit id="Suggestion">
<source>Suggestion</source>
<target state="translated">Vorschlag</target>
<note />
</trans-unit>
<trans-unit id="File_0_size_of_1_exceeds_maximum_allowed_size_of_2">
<source>File '{0}' size of {1} exceeds maximum allowed size of {2}</source>
<target state="translated">Die Größe der Datei "{0}" beträgt {1} und überschreitet so die maximal zulässige Größe von {2}.</target>
<note />
</trans-unit>
<trans-unit id="Changing_document_property_is_not_supported">
<source>Changing document properties is not supported</source>
<target state="translated">Das Ändern der Dokumenteigenschaften wird nicht unterstützt.</target>
<note />
</trans-unit>
<trans-unit id="dot_NET_Coding_Conventions">
<source>.NET Coding Conventions</source>
<target state="translated">.NET-Codierungskonventionen</target>
<note />
</trans-unit>
<trans-unit id="Variables_captured_colon">
<source>Variables captured:</source>
<target state="translated">Erfasste Variablen:</target>
<note />
</trans-unit>
</body>
</file>
</xliff> | -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/Core/CodeAnalysisTest/Collections/List/IList.NonGeneric.Tests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/IList.NonGeneric.Tests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of any class that implements the nongeneric
/// IList interface
/// </summary>
public abstract class IList_NonGeneric_Tests : ICollection_NonGeneric_Tests
{
#region IList Helper methods
/// <summary>
/// Creates an instance of an IList that can be used for testing.
/// </summary>
/// <returns>An instance of an IList that can be used for testing.</returns>
protected abstract IList NonGenericIListFactory();
/// <summary>
/// Creates an instance of an IList that can be used for testing.
/// </summary>
/// <param name="count">The number of unique items that the returned IList contains.</param>
/// <returns>An instance of an IList that can be used for testing.</returns>
protected virtual IList NonGenericIListFactory(int count)
{
IList collection = NonGenericIListFactory();
AddToCollection(collection, count);
return collection;
}
protected virtual void AddToCollection(IList collection, int numberOfItemsToAdd)
{
int seed = 9600;
while (collection.Count < numberOfItemsToAdd)
{
object toAdd = CreateT(seed++);
while (collection.Contains(toAdd) || InvalidValues.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
}
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected virtual object CreateT(int seed)
{
if (seed % 2 == 0)
{
int stringLength = seed % 10 + 5;
Random rand = new Random(seed);
byte[] bytes = new byte[stringLength];
rand.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
else
{
Random rand = new Random(seed);
return rand.Next();
}
}
protected virtual bool ExpectedFixedSize => false;
protected virtual Type IList_NonGeneric_Item_InvalidIndex_ThrowType => typeof(ArgumentOutOfRangeException);
protected virtual bool IList_NonGeneric_RemoveNonExistent_Throws => false;
/// <summary>
/// When calling Current of the enumerator after the end of the list and list is extended by new items.
/// Tests are included to cover two behavioral scenarios:
/// - Throwing an InvalidOperationException
/// - Returning an undefined value.
///
/// If this property is set to true, the tests ensure that the exception is thrown. The default value is
/// the same as Enumerator_Current_UndefinedOperation_Throws.
/// </summary>
protected virtual bool IList_CurrentAfterAdd_Throws => Enumerator_Current_UndefinedOperation_Throws;
#endregion
#region ICollection Helper Methods
protected override ICollection NonGenericICollectionFactory() => NonGenericIListFactory();
protected override ICollection NonGenericICollectionFactory(int count) => NonGenericIListFactory(count);
/// <summary>
/// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them.
/// </summary>
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations)
{
if ((operations & ModifyOperation.Add) == ModifyOperation.Add)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (!casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Add(CreateT(2344));
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Insert) == ModifyOperation.Insert)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (!casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Insert(0, CreateT(12));
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Remove) == ModifyOperation.Remove)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Remove(casted[0]);
return true;
}
return false;
};
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsFixedSize && !casted.IsReadOnly)
{
casted.RemoveAt(0);
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Overwrite) == ModifyOperation.Overwrite)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsReadOnly)
{
casted[0] = CreateT(12);
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Clear) == ModifyOperation.Clear)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Clear();
return true;
}
return false;
};
}
}
protected override void AddToCollection(ICollection collection, int numberOfItemsToAdd) => AddToCollection((IList)collection, numberOfItemsToAdd);
#endregion
#region IsFixedSize
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IsFixedSize_Validity(int count)
{
IList collection = NonGenericIListFactory(count);
Assert.Equal(ExpectedFixedSize, collection.IsFixedSize);
}
#endregion
#region IsReadOnly
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IsReadOnly_Validity(int count)
{
IList collection = NonGenericIListFactory(count);
Assert.Equal(IsReadOnly, collection.IsReadOnly);
}
#endregion
#region Item Getter
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemGet_NegativeIndex_ThrowsException(int count)
{
IList list = NonGenericIListFactory(count);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[-1]);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[int.MinValue]);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemGet_IndexGreaterThanListCount_ThrowsException(int count)
{
IList list = NonGenericIListFactory(count);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count]);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count + 1]);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemGet_ValidGetWithinListBounds(int count)
{
IList list = NonGenericIListFactory(count);
object? result;
Assert.All(Enumerable.Range(0, count), index => result = list[index]);
}
#endregion
#region Item Setter
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_NegativeIndex_ThrowsException(int count)
{
if (!IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[-1] = validAdd);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[int.MinValue] = validAdd);
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_IndexGreaterThanListCount_ThrowsException(int count)
{
if (!IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count] = validAdd);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count + 1] = validAdd);
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_OnReadOnlyList(int count)
{
if (IsReadOnly)
{
IList list = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => list[count / 2] = CreateT(321432));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_FirstItemToNonNull(int count)
{
if (count > 0 && !IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list[0] = value;
Assert.Equal(value, list[0]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_FirstItemToNull(int count)
{
if (count > 0 && !IsReadOnly && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
list[0] = value;
Assert.Equal(value, list[0]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_LastItemToNonNull(int count)
{
if (count > 0 && !IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
int lastIndex = count > 0 ? count - 1 : 0;
list[lastIndex] = value;
Assert.Equal(value, list[lastIndex]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_LastItemToNull(int count)
{
if (count > 0 && !IsReadOnly && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
int lastIndex = count > 0 ? count - 1 : 0;
list[lastIndex] = value;
Assert.Equal(value, list[lastIndex]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_DuplicateValues(int count)
{
if (count >= 2 && !IsReadOnly && DuplicateValuesAllowed)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list[0] = value;
list[1] = value;
Assert.Equal(value, list[0]);
Assert.Equal(value, list[1]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_InvalidValue(int count)
{
if (!IsReadOnly)
{
Assert.All(InvalidValues, value =>
{
IList list = NonGenericIListFactory(count);
Assert.Throws<ArgumentException>(() => list[count / 2] = value);
});
}
}
#endregion
#region Add
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_Null(int count)
{
if (NullAllowed && !IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
collection.Add(null);
Assert.Equal(count + 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_InvalidValueToMiddleOfCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, invalidValue =>
{
IList collection = NonGenericIListFactory(count);
collection.Add(invalidValue);
for (int i = 0; i < count; i++)
collection.Add(CreateT(i));
Assert.Equal(count * 2, collection.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_InvalidValueToBeginningOfCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, invalidValue =>
{
IList collection = NonGenericIListFactory(0);
collection.Add(invalidValue);
for (int i = 0; i < count; i++)
collection.Add(CreateT(i));
Assert.Equal(count, collection.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_InvalidValueToEndOfCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, invalidValue =>
{
IList collection = NonGenericIListFactory(count);
collection.Add(invalidValue);
Assert.Equal(count, collection.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_DuplicateValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
if (DuplicateValuesAllowed)
{
IList collection = NonGenericIListFactory(count);
object duplicateValue = CreateT(700);
collection.Add(duplicateValue);
collection.Add(duplicateValue);
Assert.Equal(count + 2, collection.Count);
}
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterCallingClear(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
collection.Clear();
AddToCollection(collection, 5);
Assert.Equal(5, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterRemovingAnyValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = 840;
IList collection = NonGenericIListFactory(count);
object[] items = new object[count];
collection.CopyTo(items, 0);
object toAdd = CreateT(seed++);
while (collection.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
collection.RemoveAt(0);
toAdd = CreateT(seed++);
while (collection.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterRemovingAllItems(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
object[] arr = new object[count];
collection.CopyTo(arr, 0);
for (int i = 0; i < count; i++)
collection.Remove(arr[i]);
collection.Add(CreateT(254));
Assert.Equal(1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_ToReadOnlyCollection(int count)
{
if (IsReadOnly || ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => collection.Add(CreateT(0)));
Assert.Equal(count, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterRemoving(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = 840;
IList collection = NonGenericIListFactory(count);
object toAdd = CreateT(seed++);
while (collection.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
collection.Remove(toAdd);
collection.Add(toAdd);
}
}
#endregion
#region Clear
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Clear(int count)
{
IList collection = NonGenericIListFactory(count);
if (IsReadOnly || ExpectedFixedSize)
{
Assert.Throws<NotSupportedException>(() => collection.Clear());
Assert.Equal(count, collection.Count);
}
else
{
collection.Clear();
Assert.Equal(0, collection.Count);
}
}
#endregion
#region Contains
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_ValidValueOnCollectionNotContainingThatValue(int count)
{
IList collection = NonGenericIListFactory(count);
int seed = 4315;
object item = CreateT(seed++);
while (collection.Contains(item))
item = CreateT(seed++);
Assert.False(collection.Contains(item));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IList_NonGeneric_Contains_ValidValueOnCollectionContainingThatValue(int count)
{
IList collection = NonGenericIListFactory(count);
foreach (object item in collection)
Assert.True(collection.Contains(item));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_NullOnCollectionNotContainingNull(int count)
{
IList collection = NonGenericIListFactory(count);
if (NullAllowed)
Assert.False(collection.Contains(null));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_NullOnCollectionContainingNull(int count)
{
IList collection = NonGenericIListFactory(count);
if (NullAllowed && !IsReadOnly && !ExpectedFixedSize)
{
collection.Add(null);
Assert.True(collection.Contains(null));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_ValidValueThatExistsTwiceInTheCollection(int count)
{
if (DuplicateValuesAllowed && !IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
object item = CreateT(12);
collection.Add(item);
collection.Add(item);
Assert.Equal(count + 2, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_InvalidValue_ThrowsArgumentException(int count)
{
IList collection = NonGenericIListFactory(count);
Assert.All(InvalidValues, invalidValue =>
Assert.Throws<ArgumentException>(() => collection.Contains(invalidValue))
);
}
#endregion
#region IndexOf
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_NullNotContainedInList(int count)
{
if (NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
if (list.Contains(value))
{
if (IsReadOnly || ExpectedFixedSize)
return;
list.Remove(value);
}
Assert.Equal(-1, list.IndexOf(value));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_NullContainedInList(int count)
{
if (count > 0 && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
if (!list.Contains(value))
{
if (IsReadOnly || ExpectedFixedSize)
return;
list[0] = value;
}
Assert.Equal(0, list.IndexOf(value));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_ValueInCollectionMultipleTimes(int count)
{
if (count > 0 && !IsReadOnly && !ExpectedFixedSize && DuplicateValuesAllowed)
{
// IndexOf should always return the lowest index for which a matching element is found
IList list = NonGenericIListFactory(count);
object value = CreateT(12345);
list[0] = value;
list[count / 2] = value;
Assert.Equal(0, list.IndexOf(value));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_EachValueNoDuplicates(int count)
{
// Assumes no duplicate elements contained in the list returned by NonGenericIListFactory
IList list = NonGenericIListFactory(count);
Assert.All(Enumerable.Range(0, count), index =>
{
Assert.Equal(index, list.IndexOf(list[index]));
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_InvalidValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, value =>
{
IList list = NonGenericIListFactory(count);
Assert.Throws<ArgumentException>(() => list.IndexOf(value));
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_ReturnsFirstMatchingValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object[] arr = new object[count];
list.CopyTo(arr, 0);
foreach (object duplicate in arr) // hard copies list to circumvent enumeration error
list.Add(duplicate);
object[] expected = new object[count * 2];
list.CopyTo(expected, 0);
Assert.All(Enumerable.Range(0, count), (index =>
Assert.Equal(index, list.IndexOf(expected[index]))
));
}
}
#endregion
#region Insert
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_NegativeIndex_ThrowsException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.Insert(-1, validAdd));
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.Insert(int.MinValue, validAdd));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_IndexGreaterThanListCount_Appends(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(12350);
list.Insert(count, validAdd);
Assert.Equal(count + 1, list.Count);
Assert.Equal(validAdd, list[count]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_ToReadOnlyList(int count)
{
if (IsReadOnly || ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => list.Insert(count / 2, CreateT(321432)));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_FirstItemToNonNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list.Insert(0, value);
Assert.Equal(value, list[0]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_FirstItemToNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
list.Insert(0, value);
Assert.Equal(value, list[0]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_LastItemToNonNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
int lastIndex = count > 0 ? count - 1 : 0;
list.Insert(lastIndex, value);
Assert.Equal(value, list[lastIndex]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_LastItemToNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
int lastIndex = count > 0 ? count - 1 : 0;
list.Insert(lastIndex, value);
Assert.Equal(value, list[lastIndex]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_DuplicateValues(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && DuplicateValuesAllowed)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list.Insert(0, value);
list.Insert(1, value);
Assert.Equal(value, list[0]);
Assert.Equal(value, list[1]);
Assert.Equal(count + 2, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_InvalidValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, value =>
{
IList list = NonGenericIListFactory(count);
Assert.Throws<ArgumentException>(() => list.Insert(count / 2, value));
});
}
}
#endregion
#region Remove
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IListNonGeneric_Remove_OnReadOnlyCollection_ThrowsNotSupportedException(int count)
{
if (IsReadOnly || ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => collection.Remove(CreateT(34543)));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NullNotContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed && !Enumerable.Contains(InvalidValues, null))
{
int seed = count * 21;
IList collection = NonGenericIListFactory(count);
object? value = null;
while (collection.Contains(value))
{
collection.Remove(value);
count--;
}
collection.Remove(value);
Assert.Equal(count, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NonNullNotContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = count * 251;
IList list = NonGenericIListFactory(count);
object value = CreateT(seed++);
while (list.Contains(value) || Enumerable.Contains(InvalidValues, value))
value = CreateT(seed++);
list.Remove(value);
if (IList_NonGeneric_RemoveNonExistent_Throws)
{
Assert.Throws<ArgumentException>(() => list.Remove(value));
}
else
{
Assert.Equal(count, list.Count);
}
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NullContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed && !Enumerable.Contains(InvalidValues, null))
{
int seed = count * 21;
IList collection = NonGenericIListFactory(count);
object? value = null;
if (!collection.Contains(value))
{
collection.Add(value);
count++;
}
collection.Remove(value);
Assert.Equal(count - 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NonNullContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = count * 251;
IList collection = NonGenericIListFactory(count);
object value = CreateT(seed++);
if (!collection.Contains(value))
{
collection.Add(value);
count++;
}
collection.Remove(value);
Assert.Equal(count - 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_ValueThatExistsTwiceInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && DuplicateValuesAllowed)
{
int seed = count * 90;
IList collection = NonGenericIListFactory(count);
object value = CreateT(seed++);
collection.Add(value);
collection.Add(value);
count += 2;
collection.Remove(value);
Assert.True(collection.Contains(value));
Assert.Equal(count - 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_EveryValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
object[] arr = new object[count];
collection.CopyTo(arr, 0);
Assert.All(arr, value =>
{
collection.Remove(value);
});
Assert.Empty(collection);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_InvalidValue_ThrowsArgumentException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
Assert.All(InvalidValues, value =>
{
Assert.Throws<ArgumentException>(() => collection.Remove(value));
});
Assert.Equal(count, collection.Count);
}
}
#endregion
#region RemoveAt
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_NegativeIndex_ThrowsException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(-1));
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(int.MinValue));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_IndexGreaterThanListCount_ThrowsException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(count));
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(count + 1));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_OnReadOnlyList(int count)
{
if (IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => list.RemoveAt(count / 2));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_AllValidIndices(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.Equal(count, list.Count);
Assert.All(Enumerable.Range(0, count).Reverse(), index =>
{
list.RemoveAt(index);
Assert.Equal(index, list.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_ZeroMultipleTimes(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.All(Enumerable.Range(0, count), index =>
{
list.RemoveAt(0);
Assert.Equal(count - index - 1, list.Count);
});
}
}
#endregion
#region Enumerator.Current
// Test Enumerator.Current at end after new elements was added
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_CurrentAtEnd_AfterAdd(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
IEnumerator enumerator = collection.GetEnumerator();
while (enumerator.MoveNext()) ; // Go to end of enumerator
if (Enumerator_Current_UndefinedOperation_Throws)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Enumerator.Current should fail
}
else
{
var current = enumerator.Current; // Enumerator.Current should not fail
}
// Test after add
int seed = 523561;
for (int i = 0; i < 3; i++)
{
collection.Add(CreateT(seed++));
if (IList_CurrentAfterAdd_Throws)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Enumerator.Current should fail
}
else
{
var current = enumerator.Current; // Enumerator.Current should not fail
}
}
}
}
#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.
// NOTE: This code is derived from an implementation originally in dotnet/runtime:
// https://github.com/dotnet/runtime/blob/v5.0.2/src/libraries/Common/tests/System/Collections/IList.NonGeneric.Tests.cs
//
// See the commentary in https://github.com/dotnet/roslyn/pull/50156 for notes on incorporating changes made to the
// reference implementation.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using Xunit;
namespace Microsoft.CodeAnalysis.UnitTests.Collections
{
/// <summary>
/// Contains tests that ensure the correctness of any class that implements the nongeneric
/// IList interface
/// </summary>
public abstract class IList_NonGeneric_Tests : ICollection_NonGeneric_Tests
{
#region IList Helper methods
/// <summary>
/// Creates an instance of an IList that can be used for testing.
/// </summary>
/// <returns>An instance of an IList that can be used for testing.</returns>
protected abstract IList NonGenericIListFactory();
/// <summary>
/// Creates an instance of an IList that can be used for testing.
/// </summary>
/// <param name="count">The number of unique items that the returned IList contains.</param>
/// <returns>An instance of an IList that can be used for testing.</returns>
protected virtual IList NonGenericIListFactory(int count)
{
IList collection = NonGenericIListFactory();
AddToCollection(collection, count);
return collection;
}
protected virtual void AddToCollection(IList collection, int numberOfItemsToAdd)
{
int seed = 9600;
while (collection.Count < numberOfItemsToAdd)
{
object toAdd = CreateT(seed++);
while (collection.Contains(toAdd) || InvalidValues.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
}
}
/// <summary>
/// Creates an object that is dependent on the seed given. The object may be either
/// a value type or a reference type, chosen based on the value of the seed.
/// </summary>
protected virtual object CreateT(int seed)
{
if (seed % 2 == 0)
{
int stringLength = seed % 10 + 5;
Random rand = new Random(seed);
byte[] bytes = new byte[stringLength];
rand.NextBytes(bytes);
return Convert.ToBase64String(bytes);
}
else
{
Random rand = new Random(seed);
return rand.Next();
}
}
protected virtual bool ExpectedFixedSize => false;
protected virtual Type IList_NonGeneric_Item_InvalidIndex_ThrowType => typeof(ArgumentOutOfRangeException);
protected virtual bool IList_NonGeneric_RemoveNonExistent_Throws => false;
/// <summary>
/// When calling Current of the enumerator after the end of the list and list is extended by new items.
/// Tests are included to cover two behavioral scenarios:
/// - Throwing an InvalidOperationException
/// - Returning an undefined value.
///
/// If this property is set to true, the tests ensure that the exception is thrown. The default value is
/// the same as Enumerator_Current_UndefinedOperation_Throws.
/// </summary>
protected virtual bool IList_CurrentAfterAdd_Throws => Enumerator_Current_UndefinedOperation_Throws;
#endregion
#region ICollection Helper Methods
protected override ICollection NonGenericICollectionFactory() => NonGenericIListFactory();
protected override ICollection NonGenericICollectionFactory(int count) => NonGenericIListFactory(count);
/// <summary>
/// Returns a set of ModifyEnumerable delegates that modify the enumerable passed to them.
/// </summary>
protected override IEnumerable<ModifyEnumerable> GetModifyEnumerables(ModifyOperation operations)
{
if ((operations & ModifyOperation.Add) == ModifyOperation.Add)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (!casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Add(CreateT(2344));
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Insert) == ModifyOperation.Insert)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (!casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Insert(0, CreateT(12));
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Remove) == ModifyOperation.Remove)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Remove(casted[0]);
return true;
}
return false;
};
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsFixedSize && !casted.IsReadOnly)
{
casted.RemoveAt(0);
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Overwrite) == ModifyOperation.Overwrite)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsReadOnly)
{
casted[0] = CreateT(12);
return true;
}
return false;
};
}
if ((operations & ModifyOperation.Clear) == ModifyOperation.Clear)
{
yield return (IEnumerable enumerable) =>
{
IList casted = ((IList)enumerable);
if (casted.Count > 0 && !casted.IsFixedSize && !casted.IsReadOnly)
{
casted.Clear();
return true;
}
return false;
};
}
}
protected override void AddToCollection(ICollection collection, int numberOfItemsToAdd) => AddToCollection((IList)collection, numberOfItemsToAdd);
#endregion
#region IsFixedSize
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IsFixedSize_Validity(int count)
{
IList collection = NonGenericIListFactory(count);
Assert.Equal(ExpectedFixedSize, collection.IsFixedSize);
}
#endregion
#region IsReadOnly
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IsReadOnly_Validity(int count)
{
IList collection = NonGenericIListFactory(count);
Assert.Equal(IsReadOnly, collection.IsReadOnly);
}
#endregion
#region Item Getter
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemGet_NegativeIndex_ThrowsException(int count)
{
IList list = NonGenericIListFactory(count);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[-1]);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[int.MinValue]);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemGet_IndexGreaterThanListCount_ThrowsException(int count)
{
IList list = NonGenericIListFactory(count);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count]);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count + 1]);
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemGet_ValidGetWithinListBounds(int count)
{
IList list = NonGenericIListFactory(count);
object? result;
Assert.All(Enumerable.Range(0, count), index => result = list[index]);
}
#endregion
#region Item Setter
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_NegativeIndex_ThrowsException(int count)
{
if (!IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[-1] = validAdd);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[int.MinValue] = validAdd);
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_IndexGreaterThanListCount_ThrowsException(int count)
{
if (!IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count] = validAdd);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list[count + 1] = validAdd);
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_OnReadOnlyList(int count)
{
if (IsReadOnly)
{
IList list = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => list[count / 2] = CreateT(321432));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_FirstItemToNonNull(int count)
{
if (count > 0 && !IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list[0] = value;
Assert.Equal(value, list[0]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_FirstItemToNull(int count)
{
if (count > 0 && !IsReadOnly && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
list[0] = value;
Assert.Equal(value, list[0]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_LastItemToNonNull(int count)
{
if (count > 0 && !IsReadOnly)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
int lastIndex = count > 0 ? count - 1 : 0;
list[lastIndex] = value;
Assert.Equal(value, list[lastIndex]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_LastItemToNull(int count)
{
if (count > 0 && !IsReadOnly && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
int lastIndex = count > 0 ? count - 1 : 0;
list[lastIndex] = value;
Assert.Equal(value, list[lastIndex]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_DuplicateValues(int count)
{
if (count >= 2 && !IsReadOnly && DuplicateValuesAllowed)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list[0] = value;
list[1] = value;
Assert.Equal(value, list[0]);
Assert.Equal(value, list[1]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_ItemSet_InvalidValue(int count)
{
if (!IsReadOnly)
{
Assert.All(InvalidValues, value =>
{
IList list = NonGenericIListFactory(count);
Assert.Throws<ArgumentException>(() => list[count / 2] = value);
});
}
}
#endregion
#region Add
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_Null(int count)
{
if (NullAllowed && !IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
collection.Add(null);
Assert.Equal(count + 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_InvalidValueToMiddleOfCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, invalidValue =>
{
IList collection = NonGenericIListFactory(count);
collection.Add(invalidValue);
for (int i = 0; i < count; i++)
collection.Add(CreateT(i));
Assert.Equal(count * 2, collection.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_InvalidValueToBeginningOfCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, invalidValue =>
{
IList collection = NonGenericIListFactory(0);
collection.Add(invalidValue);
for (int i = 0; i < count; i++)
collection.Add(CreateT(i));
Assert.Equal(count, collection.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_InvalidValueToEndOfCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, invalidValue =>
{
IList collection = NonGenericIListFactory(count);
collection.Add(invalidValue);
Assert.Equal(count, collection.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_DuplicateValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
if (DuplicateValuesAllowed)
{
IList collection = NonGenericIListFactory(count);
object duplicateValue = CreateT(700);
collection.Add(duplicateValue);
collection.Add(duplicateValue);
Assert.Equal(count + 2, collection.Count);
}
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterCallingClear(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
collection.Clear();
AddToCollection(collection, 5);
Assert.Equal(5, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterRemovingAnyValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = 840;
IList collection = NonGenericIListFactory(count);
object[] items = new object[count];
collection.CopyTo(items, 0);
object toAdd = CreateT(seed++);
while (collection.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
collection.RemoveAt(0);
toAdd = CreateT(seed++);
while (collection.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterRemovingAllItems(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
object[] arr = new object[count];
collection.CopyTo(arr, 0);
for (int i = 0; i < count; i++)
collection.Remove(arr[i]);
collection.Add(CreateT(254));
Assert.Equal(1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_ToReadOnlyCollection(int count)
{
if (IsReadOnly || ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => collection.Add(CreateT(0)));
Assert.Equal(count, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Add_AfterRemoving(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = 840;
IList collection = NonGenericIListFactory(count);
object toAdd = CreateT(seed++);
while (collection.Contains(toAdd))
toAdd = CreateT(seed++);
collection.Add(toAdd);
collection.Remove(toAdd);
collection.Add(toAdd);
}
}
#endregion
#region Clear
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Clear(int count)
{
IList collection = NonGenericIListFactory(count);
if (IsReadOnly || ExpectedFixedSize)
{
Assert.Throws<NotSupportedException>(() => collection.Clear());
Assert.Equal(count, collection.Count);
}
else
{
collection.Clear();
Assert.Equal(0, collection.Count);
}
}
#endregion
#region Contains
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_ValidValueOnCollectionNotContainingThatValue(int count)
{
IList collection = NonGenericIListFactory(count);
int seed = 4315;
object item = CreateT(seed++);
while (collection.Contains(item))
item = CreateT(seed++);
Assert.False(collection.Contains(item));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IList_NonGeneric_Contains_ValidValueOnCollectionContainingThatValue(int count)
{
IList collection = NonGenericIListFactory(count);
foreach (object item in collection)
Assert.True(collection.Contains(item));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_NullOnCollectionNotContainingNull(int count)
{
IList collection = NonGenericIListFactory(count);
if (NullAllowed)
Assert.False(collection.Contains(null));
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_NullOnCollectionContainingNull(int count)
{
IList collection = NonGenericIListFactory(count);
if (NullAllowed && !IsReadOnly && !ExpectedFixedSize)
{
collection.Add(null);
Assert.True(collection.Contains(null));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_ValidValueThatExistsTwiceInTheCollection(int count)
{
if (DuplicateValuesAllowed && !IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
object item = CreateT(12);
collection.Add(item);
collection.Add(item);
Assert.Equal(count + 2, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Contains_InvalidValue_ThrowsArgumentException(int count)
{
IList collection = NonGenericIListFactory(count);
Assert.All(InvalidValues, invalidValue =>
Assert.Throws<ArgumentException>(() => collection.Contains(invalidValue))
);
}
#endregion
#region IndexOf
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_NullNotContainedInList(int count)
{
if (NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
if (list.Contains(value))
{
if (IsReadOnly || ExpectedFixedSize)
return;
list.Remove(value);
}
Assert.Equal(-1, list.IndexOf(value));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_NullContainedInList(int count)
{
if (count > 0 && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
if (!list.Contains(value))
{
if (IsReadOnly || ExpectedFixedSize)
return;
list[0] = value;
}
Assert.Equal(0, list.IndexOf(value));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_ValueInCollectionMultipleTimes(int count)
{
if (count > 0 && !IsReadOnly && !ExpectedFixedSize && DuplicateValuesAllowed)
{
// IndexOf should always return the lowest index for which a matching element is found
IList list = NonGenericIListFactory(count);
object value = CreateT(12345);
list[0] = value;
list[count / 2] = value;
Assert.Equal(0, list.IndexOf(value));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_EachValueNoDuplicates(int count)
{
// Assumes no duplicate elements contained in the list returned by NonGenericIListFactory
IList list = NonGenericIListFactory(count);
Assert.All(Enumerable.Range(0, count), index =>
{
Assert.Equal(index, list.IndexOf(list[index]));
});
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_InvalidValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, value =>
{
IList list = NonGenericIListFactory(count);
Assert.Throws<ArgumentException>(() => list.IndexOf(value));
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_IndexOf_ReturnsFirstMatchingValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object[] arr = new object[count];
list.CopyTo(arr, 0);
foreach (object duplicate in arr) // hard copies list to circumvent enumeration error
list.Add(duplicate);
object[] expected = new object[count * 2];
list.CopyTo(expected, 0);
Assert.All(Enumerable.Range(0, count), (index =>
Assert.Equal(index, list.IndexOf(expected[index]))
));
}
}
#endregion
#region Insert
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_NegativeIndex_ThrowsException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.Insert(-1, validAdd));
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.Insert(int.MinValue, validAdd));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_IndexGreaterThanListCount_Appends(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(12350);
list.Insert(count, validAdd);
Assert.Equal(count + 1, list.Count);
Assert.Equal(validAdd, list[count]);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_ToReadOnlyList(int count)
{
if (IsReadOnly || ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => list.Insert(count / 2, CreateT(321432)));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_FirstItemToNonNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list.Insert(0, value);
Assert.Equal(value, list[0]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_FirstItemToNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
list.Insert(0, value);
Assert.Equal(value, list[0]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_LastItemToNonNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
int lastIndex = count > 0 ? count - 1 : 0;
list.Insert(lastIndex, value);
Assert.Equal(value, list[lastIndex]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_LastItemToNull(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed)
{
IList list = NonGenericIListFactory(count);
object? value = null;
int lastIndex = count > 0 ? count - 1 : 0;
list.Insert(lastIndex, value);
Assert.Equal(value, list[lastIndex]);
Assert.Equal(count + 1, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_DuplicateValues(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && DuplicateValuesAllowed)
{
IList list = NonGenericIListFactory(count);
object value = CreateT(123452);
list.Insert(0, value);
list.Insert(1, value);
Assert.Equal(value, list[0]);
Assert.Equal(value, list[1]);
Assert.Equal(count + 2, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Insert_InvalidValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
Assert.All(InvalidValues, value =>
{
IList list = NonGenericIListFactory(count);
Assert.Throws<ArgumentException>(() => list.Insert(count / 2, value));
});
}
}
#endregion
#region Remove
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IListNonGeneric_Remove_OnReadOnlyCollection_ThrowsNotSupportedException(int count)
{
if (IsReadOnly || ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => collection.Remove(CreateT(34543)));
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NullNotContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed && !Enumerable.Contains(InvalidValues, null))
{
int seed = count * 21;
IList collection = NonGenericIListFactory(count);
object? value = null;
while (collection.Contains(value))
{
collection.Remove(value);
count--;
}
collection.Remove(value);
Assert.Equal(count, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NonNullNotContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = count * 251;
IList list = NonGenericIListFactory(count);
object value = CreateT(seed++);
while (list.Contains(value) || Enumerable.Contains(InvalidValues, value))
value = CreateT(seed++);
list.Remove(value);
if (IList_NonGeneric_RemoveNonExistent_Throws)
{
Assert.Throws<ArgumentException>(() => list.Remove(value));
}
else
{
Assert.Equal(count, list.Count);
}
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NullContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && NullAllowed && !Enumerable.Contains(InvalidValues, null))
{
int seed = count * 21;
IList collection = NonGenericIListFactory(count);
object? value = null;
if (!collection.Contains(value))
{
collection.Add(value);
count++;
}
collection.Remove(value);
Assert.Equal(count - 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_NonNullContainedInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
int seed = count * 251;
IList collection = NonGenericIListFactory(count);
object value = CreateT(seed++);
if (!collection.Contains(value))
{
collection.Add(value);
count++;
}
collection.Remove(value);
Assert.Equal(count - 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_ValueThatExistsTwiceInCollection(int count)
{
if (!IsReadOnly && !ExpectedFixedSize && DuplicateValuesAllowed)
{
int seed = count * 90;
IList collection = NonGenericIListFactory(count);
object value = CreateT(seed++);
collection.Add(value);
collection.Add(value);
count += 2;
collection.Remove(value);
Assert.True(collection.Contains(value));
Assert.Equal(count - 1, collection.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_EveryValue(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
object[] arr = new object[count];
collection.CopyTo(arr, 0);
Assert.All(arr, value =>
{
collection.Remove(value);
});
Assert.Empty(collection);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_Remove_InvalidValue_ThrowsArgumentException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
Assert.All(InvalidValues, value =>
{
Assert.Throws<ArgumentException>(() => collection.Remove(value));
});
Assert.Equal(count, collection.Count);
}
}
#endregion
#region RemoveAt
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_NegativeIndex_ThrowsException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(-1));
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(int.MinValue));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_IndexGreaterThanListCount_ThrowsException(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
object validAdd = CreateT(0);
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(count));
Assert.Throws(IList_NonGeneric_Item_InvalidIndex_ThrowType, () => list.RemoveAt(count + 1));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_OnReadOnlyList(int count)
{
if (IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.Throws<NotSupportedException>(() => list.RemoveAt(count / 2));
Assert.Equal(count, list.Count);
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_AllValidIndices(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.Equal(count, list.Count);
Assert.All(Enumerable.Range(0, count).Reverse(), index =>
{
list.RemoveAt(index);
Assert.Equal(index, list.Count);
});
}
}
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_RemoveAt_ZeroMultipleTimes(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList list = NonGenericIListFactory(count);
Assert.All(Enumerable.Range(0, count), index =>
{
list.RemoveAt(0);
Assert.Equal(count - index - 1, list.Count);
});
}
}
#endregion
#region Enumerator.Current
// Test Enumerator.Current at end after new elements was added
[Theory]
[MemberData(nameof(ValidCollectionSizes))]
public void IList_NonGeneric_CurrentAtEnd_AfterAdd(int count)
{
if (!IsReadOnly && !ExpectedFixedSize)
{
IList collection = NonGenericIListFactory(count);
IEnumerator enumerator = collection.GetEnumerator();
while (enumerator.MoveNext()) ; // Go to end of enumerator
if (Enumerator_Current_UndefinedOperation_Throws)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Enumerator.Current should fail
}
else
{
var current = enumerator.Current; // Enumerator.Current should not fail
}
// Test after add
int seed = 523561;
for (int i = 0; i < 3; i++)
{
collection.Add(CreateT(seed++));
if (IList_CurrentAfterAdd_Throws)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Enumerator.Current should fail
}
else
{
var current = enumerator.Current; // Enumerator.Current should not fail
}
}
}
}
#endregion
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/Core/Portable/Symbols/Attributes/IMarshalAsAttributeTarget.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal interface IMarshalAsAttributeTarget
{
MarshalPseudoCustomAttributeData GetOrCreateData();
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis
{
internal interface IMarshalAsAttributeTarget
{
MarshalPseudoCustomAttributeData GetOrCreateData();
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Portable/Binder/Semantics/Operators/OperatorKindExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Linq.Expressions;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class OperatorKindExtensions
{
public static int OperatorIndex(this UnaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static UnaryOperatorKind Operator(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.OpMask;
}
public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind)
{
return kind & ~UnaryOperatorKind.Lifted;
}
public static bool IsLifted(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Lifted);
}
public static bool IsChecked(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Checked);
}
public static bool IsUserDefined(this UnaryOperatorKind kind)
{
return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined;
}
public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.Checked;
}
public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's dynamic and we're in a checked context then just mark it as checked,
// regardless of whether it is +x -x !x ~x ++x --x x++ or x--. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | UnaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.UnaryMinus:
return kind | UnaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~UnaryOperatorKind.Checked;
}
}
public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.TypeMask;
}
public static bool IsDynamic(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Dynamic;
}
public static bool IsIntegral(this UnaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case UnaryOperatorKind.SByte:
case UnaryOperatorKind.Byte:
case UnaryOperatorKind.Short:
case UnaryOperatorKind.UShort:
case UnaryOperatorKind.Int:
case UnaryOperatorKind.UInt:
case UnaryOperatorKind.Long:
case UnaryOperatorKind.ULong:
case UnaryOperatorKind.NInt:
case UnaryOperatorKind.NUInt:
case UnaryOperatorKind.Char:
case UnaryOperatorKind.Enum:
case UnaryOperatorKind.Pointer:
return true;
}
return false;
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
Debug.Assert(type == (type & UnaryOperatorKind.TypeMask));
return kind | type;
}
public static int OperatorIndex(this BinaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static BinaryOperatorKind Operator(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.OpMask;
}
public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind)
{
return kind & ~BinaryOperatorKind.Lifted;
}
public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind)
{
return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | BinaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | BinaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | BinaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | BinaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | UnaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | UnaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | UnaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | UnaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
Debug.Assert(type == (type & BinaryOperatorKind.TypeMask));
return kind | type;
}
public static bool IsLifted(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Lifted);
}
public static bool IsDynamic(this BinaryOperatorKind kind)
{
return kind.OperandTypes() == BinaryOperatorKind.Dynamic;
}
public static bool IsComparison(this BinaryOperatorKind kind)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return true;
}
return false;
}
public static bool IsChecked(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Checked);
}
public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind)
{
if (!kind.IsChecked())
{
return false;
}
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
return true;
}
return false;
}
public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's a dynamic binop then make it checked. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | BinaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
return kind | BinaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~BinaryOperatorKind.Checked;
}
}
public static bool IsEnum(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
return true;
}
return false;
}
public static bool IsEnum(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Enum;
}
public static bool IsIntegral(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int:
case BinaryOperatorKind.UInt:
case BinaryOperatorKind.Long:
case BinaryOperatorKind.ULong:
case BinaryOperatorKind.NInt:
case BinaryOperatorKind.NUInt:
case BinaryOperatorKind.Char:
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
case BinaryOperatorKind.Pointer:
case BinaryOperatorKind.PointerAndInt:
case BinaryOperatorKind.PointerAndUInt:
case BinaryOperatorKind.PointerAndLong:
case BinaryOperatorKind.PointerAndULong:
case BinaryOperatorKind.IntAndPointer:
case BinaryOperatorKind.UIntAndPointer:
case BinaryOperatorKind.LongAndPointer:
case BinaryOperatorKind.ULongAndPointer:
return true;
}
return false;
}
public static bool IsLogical(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.TypeMask;
}
public static bool IsUserDefined(this BinaryOperatorKind kind)
{
return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined;
}
public static bool IsShift(this BinaryOperatorKind kind)
{
BinaryOperatorKind type = kind.Operator();
return type == BinaryOperatorKind.LeftShift || type == BinaryOperatorKind.RightShift;
}
public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment)
{
if (isCompoundAssignment)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.MultiplyAssign;
case BinaryOperatorKind.Addition: return ExpressionType.AddAssign;
case BinaryOperatorKind.Subtraction: return ExpressionType.SubtractAssign;
case BinaryOperatorKind.Division: return ExpressionType.DivideAssign;
case BinaryOperatorKind.Remainder: return ExpressionType.ModuloAssign;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShiftAssign;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShiftAssign;
case BinaryOperatorKind.And: return ExpressionType.AndAssign;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOrAssign;
case BinaryOperatorKind.Or: return ExpressionType.OrAssign;
}
}
else
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.Multiply;
case BinaryOperatorKind.Addition: return ExpressionType.Add;
case BinaryOperatorKind.Subtraction: return ExpressionType.Subtract;
case BinaryOperatorKind.Division: return ExpressionType.Divide;
case BinaryOperatorKind.Remainder: return ExpressionType.Modulo;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShift;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShift;
case BinaryOperatorKind.Equal: return ExpressionType.Equal;
case BinaryOperatorKind.NotEqual: return ExpressionType.NotEqual;
case BinaryOperatorKind.GreaterThan: return ExpressionType.GreaterThan;
case BinaryOperatorKind.LessThan: return ExpressionType.LessThan;
case BinaryOperatorKind.GreaterThanOrEqual: return ExpressionType.GreaterThanOrEqual;
case BinaryOperatorKind.LessThanOrEqual: return ExpressionType.LessThanOrEqual;
case BinaryOperatorKind.And: return ExpressionType.And;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOr;
case BinaryOperatorKind.Or: return ExpressionType.Or;
}
}
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
public static ExpressionType ToExpressionType(this UnaryOperatorKind kind)
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
return ExpressionType.Increment;
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PrefixDecrement:
return ExpressionType.Decrement;
case UnaryOperatorKind.UnaryPlus: return ExpressionType.UnaryPlus;
case UnaryOperatorKind.UnaryMinus: return ExpressionType.Negate;
case UnaryOperatorKind.LogicalNegation: return ExpressionType.Not;
case UnaryOperatorKind.BitwiseComplement: return ExpressionType.OnesComplement;
case UnaryOperatorKind.True: return ExpressionType.IsTrue;
case UnaryOperatorKind.False: return ExpressionType.IsFalse;
default:
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
}
#if DEBUG
public static string Dump(this BinaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & BinaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & BinaryOperatorKind.Logical) != 0) b.Append("Logical");
if ((kind & BinaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & BinaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & BinaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
public static string Dump(this UnaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & UnaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & UnaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & UnaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & UnaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
#endif
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Diagnostics;
using System.Linq.Expressions;
using System.Text;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp
{
internal static partial class OperatorKindExtensions
{
public static int OperatorIndex(this UnaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static UnaryOperatorKind Operator(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.OpMask;
}
public static UnaryOperatorKind Unlifted(this UnaryOperatorKind kind)
{
return kind & ~UnaryOperatorKind.Lifted;
}
public static bool IsLifted(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Lifted);
}
public static bool IsChecked(this UnaryOperatorKind kind)
{
return 0 != (kind & UnaryOperatorKind.Checked);
}
public static bool IsUserDefined(this UnaryOperatorKind kind)
{
return (kind & UnaryOperatorKind.TypeMask) == UnaryOperatorKind.UserDefined;
}
public static UnaryOperatorKind OverflowChecks(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.Checked;
}
public static UnaryOperatorKind WithOverflowChecksIfApplicable(this UnaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's dynamic and we're in a checked context then just mark it as checked,
// regardless of whether it is +x -x !x ~x ++x --x x++ or x--. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | UnaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
case UnaryOperatorKind.PrefixDecrement:
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.UnaryMinus:
return kind | UnaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~UnaryOperatorKind.Checked;
}
}
public static UnaryOperatorKind OperandTypes(this UnaryOperatorKind kind)
{
return kind & UnaryOperatorKind.TypeMask;
}
public static bool IsDynamic(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Dynamic;
}
public static bool IsIntegral(this UnaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case UnaryOperatorKind.SByte:
case UnaryOperatorKind.Byte:
case UnaryOperatorKind.Short:
case UnaryOperatorKind.UShort:
case UnaryOperatorKind.Int:
case UnaryOperatorKind.UInt:
case UnaryOperatorKind.Long:
case UnaryOperatorKind.ULong:
case UnaryOperatorKind.NInt:
case UnaryOperatorKind.NUInt:
case UnaryOperatorKind.Char:
case UnaryOperatorKind.Enum:
case UnaryOperatorKind.Pointer:
return true;
}
return false;
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, UnaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
Debug.Assert(type == (type & UnaryOperatorKind.TypeMask));
return kind | type;
}
public static int OperatorIndex(this BinaryOperatorKind kind)
{
return ((int)kind.Operator() >> 8) - 16;
}
public static BinaryOperatorKind Operator(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.OpMask;
}
public static BinaryOperatorKind Unlifted(this BinaryOperatorKind kind)
{
return kind & ~BinaryOperatorKind.Lifted;
}
public static BinaryOperatorKind OperatorWithLogical(this BinaryOperatorKind kind)
{
return kind & (BinaryOperatorKind.OpMask | BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | BinaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | BinaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | BinaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | BinaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static UnaryOperatorKind WithType(this UnaryOperatorKind kind, SpecialType type)
{
Debug.Assert(kind == (kind & ~UnaryOperatorKind.TypeMask));
switch (type)
{
case SpecialType.System_Int32:
return kind | UnaryOperatorKind.Int;
case SpecialType.System_UInt32:
return kind | UnaryOperatorKind.UInt;
case SpecialType.System_Int64:
return kind | UnaryOperatorKind.Long;
case SpecialType.System_UInt64:
return kind | UnaryOperatorKind.ULong;
default:
throw ExceptionUtilities.UnexpectedValue(type);
}
}
public static BinaryOperatorKind WithType(this BinaryOperatorKind kind, BinaryOperatorKind type)
{
Debug.Assert(kind == (kind & ~BinaryOperatorKind.TypeMask));
Debug.Assert(type == (type & BinaryOperatorKind.TypeMask));
return kind | type;
}
public static bool IsLifted(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Lifted);
}
public static bool IsDynamic(this BinaryOperatorKind kind)
{
return kind.OperandTypes() == BinaryOperatorKind.Dynamic;
}
public static bool IsComparison(this BinaryOperatorKind kind)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Equal:
case BinaryOperatorKind.NotEqual:
case BinaryOperatorKind.GreaterThan:
case BinaryOperatorKind.GreaterThanOrEqual:
case BinaryOperatorKind.LessThan:
case BinaryOperatorKind.LessThanOrEqual:
return true;
}
return false;
}
public static bool IsChecked(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Checked);
}
public static bool EmitsAsCheckedInstruction(this BinaryOperatorKind kind)
{
if (!kind.IsChecked())
{
return false;
}
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
return true;
}
return false;
}
public static BinaryOperatorKind WithOverflowChecksIfApplicable(this BinaryOperatorKind kind, bool enabled)
{
if (enabled)
{
// If it's a dynamic binop then make it checked. Let the lowering
// pass sort out what to do with it.
if (kind.IsDynamic())
{
return kind | BinaryOperatorKind.Checked;
}
if (kind.IsIntegral())
{
switch (kind.Operator())
{
case BinaryOperatorKind.Addition:
case BinaryOperatorKind.Subtraction:
case BinaryOperatorKind.Multiplication:
case BinaryOperatorKind.Division:
return kind | BinaryOperatorKind.Checked;
}
}
return kind;
}
else
{
return kind & ~BinaryOperatorKind.Checked;
}
}
public static bool IsEnum(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
return true;
}
return false;
}
public static bool IsEnum(this UnaryOperatorKind kind)
{
return kind.OperandTypes() == UnaryOperatorKind.Enum;
}
public static bool IsIntegral(this BinaryOperatorKind kind)
{
switch (kind.OperandTypes())
{
case BinaryOperatorKind.Int:
case BinaryOperatorKind.UInt:
case BinaryOperatorKind.Long:
case BinaryOperatorKind.ULong:
case BinaryOperatorKind.NInt:
case BinaryOperatorKind.NUInt:
case BinaryOperatorKind.Char:
case BinaryOperatorKind.Enum:
case BinaryOperatorKind.EnumAndUnderlying:
case BinaryOperatorKind.UnderlyingAndEnum:
case BinaryOperatorKind.Pointer:
case BinaryOperatorKind.PointerAndInt:
case BinaryOperatorKind.PointerAndUInt:
case BinaryOperatorKind.PointerAndLong:
case BinaryOperatorKind.PointerAndULong:
case BinaryOperatorKind.IntAndPointer:
case BinaryOperatorKind.UIntAndPointer:
case BinaryOperatorKind.LongAndPointer:
case BinaryOperatorKind.ULongAndPointer:
return true;
}
return false;
}
public static bool IsLogical(this BinaryOperatorKind kind)
{
return 0 != (kind & BinaryOperatorKind.Logical);
}
public static BinaryOperatorKind OperandTypes(this BinaryOperatorKind kind)
{
return kind & BinaryOperatorKind.TypeMask;
}
public static bool IsUserDefined(this BinaryOperatorKind kind)
{
return (kind & BinaryOperatorKind.TypeMask) == BinaryOperatorKind.UserDefined;
}
public static bool IsShift(this BinaryOperatorKind kind)
{
BinaryOperatorKind type = kind.Operator();
return type == BinaryOperatorKind.LeftShift || type == BinaryOperatorKind.RightShift;
}
public static ExpressionType ToExpressionType(this BinaryOperatorKind kind, bool isCompoundAssignment)
{
if (isCompoundAssignment)
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.MultiplyAssign;
case BinaryOperatorKind.Addition: return ExpressionType.AddAssign;
case BinaryOperatorKind.Subtraction: return ExpressionType.SubtractAssign;
case BinaryOperatorKind.Division: return ExpressionType.DivideAssign;
case BinaryOperatorKind.Remainder: return ExpressionType.ModuloAssign;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShiftAssign;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShiftAssign;
case BinaryOperatorKind.And: return ExpressionType.AndAssign;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOrAssign;
case BinaryOperatorKind.Or: return ExpressionType.OrAssign;
}
}
else
{
switch (kind.Operator())
{
case BinaryOperatorKind.Multiplication: return ExpressionType.Multiply;
case BinaryOperatorKind.Addition: return ExpressionType.Add;
case BinaryOperatorKind.Subtraction: return ExpressionType.Subtract;
case BinaryOperatorKind.Division: return ExpressionType.Divide;
case BinaryOperatorKind.Remainder: return ExpressionType.Modulo;
case BinaryOperatorKind.LeftShift: return ExpressionType.LeftShift;
case BinaryOperatorKind.RightShift: return ExpressionType.RightShift;
case BinaryOperatorKind.Equal: return ExpressionType.Equal;
case BinaryOperatorKind.NotEqual: return ExpressionType.NotEqual;
case BinaryOperatorKind.GreaterThan: return ExpressionType.GreaterThan;
case BinaryOperatorKind.LessThan: return ExpressionType.LessThan;
case BinaryOperatorKind.GreaterThanOrEqual: return ExpressionType.GreaterThanOrEqual;
case BinaryOperatorKind.LessThanOrEqual: return ExpressionType.LessThanOrEqual;
case BinaryOperatorKind.And: return ExpressionType.And;
case BinaryOperatorKind.Xor: return ExpressionType.ExclusiveOr;
case BinaryOperatorKind.Or: return ExpressionType.Or;
}
}
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
public static ExpressionType ToExpressionType(this UnaryOperatorKind kind)
{
switch (kind.Operator())
{
case UnaryOperatorKind.PrefixIncrement:
case UnaryOperatorKind.PostfixIncrement:
return ExpressionType.Increment;
case UnaryOperatorKind.PostfixDecrement:
case UnaryOperatorKind.PrefixDecrement:
return ExpressionType.Decrement;
case UnaryOperatorKind.UnaryPlus: return ExpressionType.UnaryPlus;
case UnaryOperatorKind.UnaryMinus: return ExpressionType.Negate;
case UnaryOperatorKind.LogicalNegation: return ExpressionType.Not;
case UnaryOperatorKind.BitwiseComplement: return ExpressionType.OnesComplement;
case UnaryOperatorKind.True: return ExpressionType.IsTrue;
case UnaryOperatorKind.False: return ExpressionType.IsFalse;
default:
throw ExceptionUtilities.UnexpectedValue(kind.Operator());
}
}
#if DEBUG
public static string Dump(this BinaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & BinaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & BinaryOperatorKind.Logical) != 0) b.Append("Logical");
if ((kind & BinaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & BinaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & BinaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
public static string Dump(this UnaryOperatorKind kind)
{
var b = new StringBuilder();
if ((kind & UnaryOperatorKind.Lifted) != 0) b.Append("Lifted");
if ((kind & UnaryOperatorKind.Checked) != 0) b.Append("Checked");
var type = kind & UnaryOperatorKind.TypeMask;
if (type != 0) b.Append(type.ToString());
var op = kind & UnaryOperatorKind.OpMask;
if (op != 0) b.Append(op.ToString());
return b.ToString();
}
#endif
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/VisualBasicTest/Recommendations/PreprocessorDirectives/EndIfDirectiveKeywordRecommenderTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives
Public Class EndIfDirectiveKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfNotInFileTest()
VerifyRecommendationsMissing(<File>|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfInFileAfterIfTest()
VerifyRecommendationsContain(<File>
#If True Then
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfInFileAfterElseIfTest()
VerifyRecommendationsContain(<File>
#If True Then
#ElseIf True Then
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfNotInFileAfterElse1Test()
VerifyRecommendationsContain(<File>
#If True Then
#Else
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfNotInFileAfterElse2Test()
VerifyRecommendationsContain(<File>
#If True Then
#ElseIf True Then
#Else
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub IfAfterHashEndIfTest()
VerifyRecommendationsContain(<File>
#If True Then
#ElseIf True Then
#End |</File>, "If")
End Sub
<WorkItem(957458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957458")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotIfWithEndPartiallyTypedTest()
VerifyRecommendationsMissing(<File>
#If True Then
#En |</File>, "If")
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.PreprocessorDirectives
Public Class EndIfDirectiveKeywordRecommenderTests
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfNotInFileTest()
VerifyRecommendationsMissing(<File>|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfInFileAfterIfTest()
VerifyRecommendationsContain(<File>
#If True Then
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfInFileAfterElseIfTest()
VerifyRecommendationsContain(<File>
#If True Then
#ElseIf True Then
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfNotInFileAfterElse1Test()
VerifyRecommendationsContain(<File>
#If True Then
#Else
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub HashEndIfNotInFileAfterElse2Test()
VerifyRecommendationsContain(<File>
#If True Then
#ElseIf True Then
#Else
|</File>, "#End If")
End Sub
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub IfAfterHashEndIfTest()
VerifyRecommendationsContain(<File>
#If True Then
#ElseIf True Then
#End |</File>, "If")
End Sub
<WorkItem(957458, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/957458")>
<Fact>
<Trait(Traits.Feature, Traits.Features.KeywordRecommending)>
Public Sub NotIfWithEndPartiallyTypedTest()
VerifyRecommendationsMissing(<File>
#If True Then
#En |</File>, "If")
End Sub
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/Core/Portable/EmbeddedLanguages/RegularExpressions/RegexNode.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
internal abstract class RegexNode : EmbeddedSyntaxNode<RegexKind, RegexNode>
{
protected RegexNode(RegexKind kind) : base(kind)
{
}
public abstract void Accept(IRegexNodeVisitor visitor);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.RegularExpressions
{
internal abstract class RegexNode : EmbeddedSyntaxNode<RegexKind, RegexNode>
{
protected RegexNode(RegexKind kind) : base(kind)
{
}
public abstract void Accept(IRegexNodeVisitor visitor);
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/VisualStudio/VisualBasic/Impl/Options/AutomationObject/AutomationObject.DocumentationComment.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.DocumentationComments
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Partial Public Class AutomationObject
Public Property AutoComment As Boolean
Get
Return GetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration)
End Get
Set(value As Boolean)
SetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, value)
End Set
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.DocumentationComments
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Partial Public Class AutomationObject
Public Property AutoComment As Boolean
Get
Return GetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration)
End Get
Set(value As Boolean)
SetBooleanOption(DocumentationCommentOptions.AutoXmlDocCommentGeneration, value)
End Set
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/VisualStudio/Core/Def/Implementation/LanguageService/AbstractLanguageService`2.IVsLanguageTextOps.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using RoslynTextSpan = Microsoft.CodeAnalysis.Text.TextSpan;
using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsLanguageTextOps
where TPackage : AbstractPackage<TPackage, TLanguageService>
where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
{
public int Format(IVsTextLayer textLayer, TextSpan[] selections)
{
var result = VSConstants.S_OK;
var uiThreadOperationExecutor = this.Package.ComponentModel.GetService<IUIThreadOperationExecutor>();
uiThreadOperationExecutor.Execute(
"Intellisense",
defaultDescription: "",
allowCancellation: true,
showProgress: false,
action: c => result = FormatWorker(textLayer, selections, c.UserCancellationToken));
return result;
}
private int FormatWorker(IVsTextLayer textLayer, TextSpan[] selections, CancellationToken cancellationToken)
{
var textBuffer = this.EditorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)textLayer);
if (textBuffer == null)
{
return VSConstants.E_UNEXPECTED;
}
var document = textBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return VSConstants.E_FAIL;
}
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var text = root.SyntaxTree.GetText(cancellationToken);
var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var ts = selections.Single();
var start = text.Lines[ts.iStartLine].Start + ts.iStartIndex;
var end = text.Lines[ts.iEndLine].Start + ts.iEndIndex;
var adjustedSpan = GetFormattingSpan(root, start, end);
// Since we know we are on the UI thread, lets get the base indentation now, so that there is less
// cleanup work to do later in Venus.
var ruleFactory = this.Workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>();
var rules = ruleFactory.CreateRule(document, start).Concat(Formatter.GetDefaultFormattingRules(document));
// use formatting that return text changes rather than tree rewrite which is more expensive
var originalChanges = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(adjustedSpan), document.Project.Solution.Workspace, options, rules, cancellationToken);
var originalSpan = RoslynTextSpan.FromBounds(start, end);
var formattedChanges = ruleFactory.FilterFormattedChanges(document, originalSpan, originalChanges);
if (formattedChanges.IsEmpty())
{
return VSConstants.S_OK;
}
// create new formatted document
var formattedDocument = document.WithText(text.WithChanges(formattedChanges));
formattedDocument.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken);
return VSConstants.S_OK;
}
private static RoslynTextSpan GetFormattingSpan(SyntaxNode root, int start, int end)
{
// HACK: The formatting engine is inclusive in it's spans, so it won't insert
// adjust the indentation if there is a token right at the spans we start at.
// Instead, we make sure we include preceding indentation.
var prevToken = root.FindToken(start).GetPreviousToken();
if (prevToken != default)
{
start = prevToken.Span.Start;
}
var nextToken = root.FindTokenFromEnd(end).GetNextToken();
if (nextToken != default)
{
end = nextToken.Span.End;
}
return RoslynTextSpan.FromBounds(start, end);
}
public int GetDataTip(IVsTextLayer textLayer, TextSpan[] selection, TextSpan[] tipSpan, out string text)
{
text = null;
return VSConstants.E_NOTIMPL;
}
public int GetPairExtent(IVsTextLayer textLayer, TextAddress ta, TextSpan[] textSpan)
=> VSConstants.E_NOTIMPL;
public int GetWordExtent(IVsTextLayer textLayer, TextAddress ta, WORDEXTFLAGS flags, TextSpan[] textSpan)
=> VSConstants.E_NOTIMPL;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.TextManager.Interop;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using RoslynTextSpan = Microsoft.CodeAnalysis.Text.TextSpan;
using TextSpan = Microsoft.VisualStudio.TextManager.Interop.TextSpan;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.LanguageService
{
internal abstract partial class AbstractLanguageService<TPackage, TLanguageService> : IVsLanguageTextOps
where TPackage : AbstractPackage<TPackage, TLanguageService>
where TLanguageService : AbstractLanguageService<TPackage, TLanguageService>
{
public int Format(IVsTextLayer textLayer, TextSpan[] selections)
{
var result = VSConstants.S_OK;
var uiThreadOperationExecutor = this.Package.ComponentModel.GetService<IUIThreadOperationExecutor>();
uiThreadOperationExecutor.Execute(
"Intellisense",
defaultDescription: "",
allowCancellation: true,
showProgress: false,
action: c => result = FormatWorker(textLayer, selections, c.UserCancellationToken));
return result;
}
private int FormatWorker(IVsTextLayer textLayer, TextSpan[] selections, CancellationToken cancellationToken)
{
var textBuffer = this.EditorAdaptersFactoryService.GetDataBuffer((IVsTextBuffer)textLayer);
if (textBuffer == null)
{
return VSConstants.E_UNEXPECTED;
}
var document = textBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
if (document == null)
{
return VSConstants.E_FAIL;
}
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var text = root.SyntaxTree.GetText(cancellationToken);
var options = document.GetOptionsAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var ts = selections.Single();
var start = text.Lines[ts.iStartLine].Start + ts.iStartIndex;
var end = text.Lines[ts.iEndLine].Start + ts.iEndIndex;
var adjustedSpan = GetFormattingSpan(root, start, end);
// Since we know we are on the UI thread, lets get the base indentation now, so that there is less
// cleanup work to do later in Venus.
var ruleFactory = this.Workspace.Services.GetService<IHostDependentFormattingRuleFactoryService>();
var rules = ruleFactory.CreateRule(document, start).Concat(Formatter.GetDefaultFormattingRules(document));
// use formatting that return text changes rather than tree rewrite which is more expensive
var originalChanges = Formatter.GetFormattedTextChanges(root, SpecializedCollections.SingletonEnumerable(adjustedSpan), document.Project.Solution.Workspace, options, rules, cancellationToken);
var originalSpan = RoslynTextSpan.FromBounds(start, end);
var formattedChanges = ruleFactory.FilterFormattedChanges(document, originalSpan, originalChanges);
if (formattedChanges.IsEmpty())
{
return VSConstants.S_OK;
}
// create new formatted document
var formattedDocument = document.WithText(text.WithChanges(formattedChanges));
formattedDocument.Project.Solution.Workspace.ApplyDocumentChanges(formattedDocument, cancellationToken);
return VSConstants.S_OK;
}
private static RoslynTextSpan GetFormattingSpan(SyntaxNode root, int start, int end)
{
// HACK: The formatting engine is inclusive in it's spans, so it won't insert
// adjust the indentation if there is a token right at the spans we start at.
// Instead, we make sure we include preceding indentation.
var prevToken = root.FindToken(start).GetPreviousToken();
if (prevToken != default)
{
start = prevToken.Span.Start;
}
var nextToken = root.FindTokenFromEnd(end).GetNextToken();
if (nextToken != default)
{
end = nextToken.Span.End;
}
return RoslynTextSpan.FromBounds(start, end);
}
public int GetDataTip(IVsTextLayer textLayer, TextSpan[] selection, TextSpan[] tipSpan, out string text)
{
text = null;
return VSConstants.E_NOTIMPL;
}
public int GetPairExtent(IVsTextLayer textLayer, TextAddress ta, TextSpan[] textSpan)
=> VSConstants.E_NOTIMPL;
public int GetWordExtent(IVsTextLayer textLayer, TextAddress ta, WORDEXTFLAGS flags, TextSpan[] textSpan)
=> VSConstants.E_NOTIMPL;
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/Queries/EqualsKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the Equals keyword when in a join syntax.
''' </summary>
Friend Class EqualsKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Equals", VBFeaturesResources.Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.SyntaxTree.IsFollowingCompleteExpression(Of JoinConditionSyntax)(context.Position, context.TargetToken, Function(joinCondition) joinCondition.Left, cancellationToken),
s_keywords,
ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.Queries
''' <summary>
''' Recommends the Equals keyword when in a join syntax.
''' </summary>
Friend Class EqualsKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("Equals", VBFeaturesResources.Specifies_the_relationship_between_element_keys_to_use_as_the_basis_of_a_join_operation))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.SyntaxTree.IsFollowingCompleteExpression(Of JoinConditionSyntax)(context.Position, context.TargetToken, Function(joinCondition) joinCondition.Left, cancellationToken),
s_keywords,
ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Test/Semantic/SourceGeneration/AdditionalSourcesCollectionTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class AdditionalSourcesCollectionTests
: CSharpTestBase
{
[Theory]
[InlineData("abc")] // abc.cs
[InlineData("abc.cs")] //abc.cs
[InlineData("abc.vb")] // abc.vb.cs
[InlineData("abc.generated.cs")]
[InlineData("abc_-_")]
[InlineData("abc - generated.cs")]
[InlineData("abc\u0064.cs")] //acbd.cs
[InlineData("abc(1).cs")]
[InlineData("abc[1].cs")]
[InlineData("abc{1}.cs")]
public void HintName_ValidValues(string hintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8));
Assert.True(asc.Contains(hintName));
var sources = asc.ToImmutableAndFree();
Assert.Single(sources);
Assert.True(sources[0].HintName.EndsWith(".cs"));
}
[Theory]
[InlineData("abc")] // abc.vb
[InlineData("abc.cs")] //abc.cs.vb
[InlineData("abc.vb")] // abc.vb
public void HintName_WithExtension(string hintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb");
asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8));
Assert.True(asc.Contains(hintName));
var sources = asc.ToImmutableAndFree();
Assert.Single(sources);
Assert.True(sources[0].HintName.EndsWith(".vb"));
}
[Theory]
[InlineData("/abc/def.cs")]
[InlineData("\\")]
[InlineData(":")]
[InlineData("*")]
[InlineData("?")]
[InlineData("\"")]
[InlineData("<")]
[InlineData(">")]
[InlineData("|")]
[InlineData("\0")]
[InlineData("abc\u00A0.cs")] // unicode non-breaking space
public void HintName_InvalidValues(string hintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)));
Assert.Contains(hintName, exception.Message);
}
[Fact]
public void AddedSources_Are_Deterministic()
{
// a few manual simple ones
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add("file3.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file1.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file2.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file5.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file4.cs", SourceText.From("", Encoding.UTF8));
var sources = asc.ToImmutableAndFree();
var hintNames = sources.Select(s => s.HintName).ToArray();
Assert.Equal(new[]
{
"file3.cs",
"file1.cs",
"file2.cs",
"file5.cs",
"file4.cs"
}, hintNames);
// generate a long random list, remembering the order we added them
Random r = new Random();
string[] names = new string[1000];
asc = new AdditionalSourcesCollection(".cs");
for (int i = 0; i < 1000; i++)
{
names[i] = CSharpTestBase.GetUniqueName() + ".cs";
asc.Add(names[i], SourceText.From("", Encoding.UTF8));
}
sources = asc.ToImmutableAndFree();
hintNames = sources.Select(s => s.HintName).ToArray();
Assert.Equal(names, hintNames);
}
[Theory]
[InlineData("file.cs", "file.cs")]
[InlineData("file", "file")]
[InlineData("file", "file.cs")]
[InlineData("file.cs", "file")]
[InlineData("file.cs", "file.CS")]
[InlineData("file.CS", "file.cs")]
[InlineData("file", "file.CS")]
[InlineData("file.CS", "file")]
[InlineData("File", "file")]
[InlineData("file", "File")]
public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(hintName1, SourceText.From("", Encoding.UTF8));
var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8)));
Assert.Contains(hintName2, exception.Message);
}
[Fact]
public void Hint_Name_Must_Be_Unique_When_Combining_Soruces()
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add("hintName1", SourceText.From("", Encoding.UTF8));
asc.Add("hintName2", SourceText.From("", Encoding.UTF8));
AdditionalSourcesCollection asc2 = new AdditionalSourcesCollection(".cs");
asc2.Add("hintName3", SourceText.From("", Encoding.UTF8));
asc2.Add("hintName1", SourceText.From("", Encoding.UTF8));
var exception = Assert.Throws<ArgumentException>("hintName", () => asc.CopyTo(asc2));
Assert.Contains("hintName1", exception.Message);
}
[Theory]
[InlineData("file.cs", "file.cs")]
[InlineData("file", "file")]
[InlineData("file", "file.cs")]
[InlineData("file.cs", "file")]
[InlineData("file.CS", "file")]
[InlineData("file", "file.CS")]
[InlineData("File", "file.cs")]
[InlineData("File.cs", "file")]
[InlineData("File.cs", "file.CS")]
public void Contains(string addHintName, string checkHintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(addHintName, SourceText.From("", Encoding.UTF8));
Assert.True(asc.Contains(checkHintName));
}
[Theory]
[InlineData("file.cs", "file.cs")]
[InlineData("file", "file")]
[InlineData("file", "file.cs")]
[InlineData("file.cs", "file")]
public void Remove(string addHintName, string removeHintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(addHintName, SourceText.From("", Encoding.UTF8));
asc.RemoveSource(removeHintName);
var sources = asc.ToImmutableAndFree();
Assert.Empty(sources);
}
[Fact]
public void SourceTextRequiresEncoding()
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
// fine
asc.Add("file1.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file2.cs", SourceText.From("", Encoding.UTF32));
asc.Add("file3.cs", SourceText.From("", Encoding.Unicode));
// no encoding
Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From("")));
// explicit null encoding
Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null)));
var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null)));
// check the exception contains the expected hintName
Assert.Contains("file5.cs", exception.Message);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.Semantic.UnitTests.SourceGeneration
{
public class AdditionalSourcesCollectionTests
: CSharpTestBase
{
[Theory]
[InlineData("abc")] // abc.cs
[InlineData("abc.cs")] //abc.cs
[InlineData("abc.vb")] // abc.vb.cs
[InlineData("abc.generated.cs")]
[InlineData("abc_-_")]
[InlineData("abc - generated.cs")]
[InlineData("abc\u0064.cs")] //acbd.cs
[InlineData("abc(1).cs")]
[InlineData("abc[1].cs")]
[InlineData("abc{1}.cs")]
public void HintName_ValidValues(string hintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8));
Assert.True(asc.Contains(hintName));
var sources = asc.ToImmutableAndFree();
Assert.Single(sources);
Assert.True(sources[0].HintName.EndsWith(".cs"));
}
[Theory]
[InlineData("abc")] // abc.vb
[InlineData("abc.cs")] //abc.cs.vb
[InlineData("abc.vb")] // abc.vb
public void HintName_WithExtension(string hintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".vb");
asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8));
Assert.True(asc.Contains(hintName));
var sources = asc.ToImmutableAndFree();
Assert.Single(sources);
Assert.True(sources[0].HintName.EndsWith(".vb"));
}
[Theory]
[InlineData("/abc/def.cs")]
[InlineData("\\")]
[InlineData(":")]
[InlineData("*")]
[InlineData("?")]
[InlineData("\"")]
[InlineData("<")]
[InlineData(">")]
[InlineData("|")]
[InlineData("\0")]
[InlineData("abc\u00A0.cs")] // unicode non-breaking space
public void HintName_InvalidValues(string hintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
var exception = Assert.Throws<ArgumentException>(nameof(hintName), () => asc.Add(hintName, SourceText.From("public class D{}", Encoding.UTF8)));
Assert.Contains(hintName, exception.Message);
}
[Fact]
public void AddedSources_Are_Deterministic()
{
// a few manual simple ones
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add("file3.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file1.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file2.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file5.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file4.cs", SourceText.From("", Encoding.UTF8));
var sources = asc.ToImmutableAndFree();
var hintNames = sources.Select(s => s.HintName).ToArray();
Assert.Equal(new[]
{
"file3.cs",
"file1.cs",
"file2.cs",
"file5.cs",
"file4.cs"
}, hintNames);
// generate a long random list, remembering the order we added them
Random r = new Random();
string[] names = new string[1000];
asc = new AdditionalSourcesCollection(".cs");
for (int i = 0; i < 1000; i++)
{
names[i] = CSharpTestBase.GetUniqueName() + ".cs";
asc.Add(names[i], SourceText.From("", Encoding.UTF8));
}
sources = asc.ToImmutableAndFree();
hintNames = sources.Select(s => s.HintName).ToArray();
Assert.Equal(names, hintNames);
}
[Theory]
[InlineData("file.cs", "file.cs")]
[InlineData("file", "file")]
[InlineData("file", "file.cs")]
[InlineData("file.cs", "file")]
[InlineData("file.cs", "file.CS")]
[InlineData("file.CS", "file.cs")]
[InlineData("file", "file.CS")]
[InlineData("file.CS", "file")]
[InlineData("File", "file")]
[InlineData("file", "File")]
public void Hint_Name_Must_Be_Unique(string hintName1, string hintName2)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(hintName1, SourceText.From("", Encoding.UTF8));
var exception = Assert.Throws<ArgumentException>("hintName", () => asc.Add(hintName2, SourceText.From("", Encoding.UTF8)));
Assert.Contains(hintName2, exception.Message);
}
[Fact]
public void Hint_Name_Must_Be_Unique_When_Combining_Soruces()
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add("hintName1", SourceText.From("", Encoding.UTF8));
asc.Add("hintName2", SourceText.From("", Encoding.UTF8));
AdditionalSourcesCollection asc2 = new AdditionalSourcesCollection(".cs");
asc2.Add("hintName3", SourceText.From("", Encoding.UTF8));
asc2.Add("hintName1", SourceText.From("", Encoding.UTF8));
var exception = Assert.Throws<ArgumentException>("hintName", () => asc.CopyTo(asc2));
Assert.Contains("hintName1", exception.Message);
}
[Theory]
[InlineData("file.cs", "file.cs")]
[InlineData("file", "file")]
[InlineData("file", "file.cs")]
[InlineData("file.cs", "file")]
[InlineData("file.CS", "file")]
[InlineData("file", "file.CS")]
[InlineData("File", "file.cs")]
[InlineData("File.cs", "file")]
[InlineData("File.cs", "file.CS")]
public void Contains(string addHintName, string checkHintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(addHintName, SourceText.From("", Encoding.UTF8));
Assert.True(asc.Contains(checkHintName));
}
[Theory]
[InlineData("file.cs", "file.cs")]
[InlineData("file", "file")]
[InlineData("file", "file.cs")]
[InlineData("file.cs", "file")]
public void Remove(string addHintName, string removeHintName)
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
asc.Add(addHintName, SourceText.From("", Encoding.UTF8));
asc.RemoveSource(removeHintName);
var sources = asc.ToImmutableAndFree();
Assert.Empty(sources);
}
[Fact]
public void SourceTextRequiresEncoding()
{
AdditionalSourcesCollection asc = new AdditionalSourcesCollection(".cs");
// fine
asc.Add("file1.cs", SourceText.From("", Encoding.UTF8));
asc.Add("file2.cs", SourceText.From("", Encoding.UTF32));
asc.Add("file3.cs", SourceText.From("", Encoding.Unicode));
// no encoding
Assert.Throws<ArgumentException>(() => asc.Add("file4.cs", SourceText.From("")));
// explicit null encoding
Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null)));
var exception = Assert.Throws<ArgumentException>(() => asc.Add("file5.cs", SourceText.From("", encoding: null)));
// check the exception contains the expected hintName
Assert.Contains("file5.cs", exception.Message);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/ExpressionEvaluator/Core/Source/ExpressionCompiler/ExpressionCompilerConstants.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class ExpressionCompilerConstants
{
internal const string TypeVariablesLocalName = "<>TypeVariables";
internal const string TypeVariablesClassName = "<>c__TypeVariables";
internal const string IntrinsicAssemblyNamespace = "Microsoft.VisualStudio.Debugger.Clr";
internal const string IntrinsicAssemblyTypeName = "IntrinsicMethods";
internal const string IntrinsicAssemblyTypeMetadataName = IntrinsicAssemblyNamespace + "." + IntrinsicAssemblyTypeName;
internal const string GetExceptionMethodName = "GetException";
internal const string GetStowedExceptionMethodName = "GetStowedException";
internal const string GetObjectAtAddressMethodName = "GetObjectAtAddress";
internal const string GetReturnValueMethodName = "GetReturnValue";
internal const string CreateVariableMethodName = "CreateVariable";
internal const string GetVariableValueMethodName = "GetObjectByAlias";
internal const string GetVariableAddressMethodName = "GetVariableAddress";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.ExpressionEvaluator
{
internal static class ExpressionCompilerConstants
{
internal const string TypeVariablesLocalName = "<>TypeVariables";
internal const string TypeVariablesClassName = "<>c__TypeVariables";
internal const string IntrinsicAssemblyNamespace = "Microsoft.VisualStudio.Debugger.Clr";
internal const string IntrinsicAssemblyTypeName = "IntrinsicMethods";
internal const string IntrinsicAssemblyTypeMetadataName = IntrinsicAssemblyNamespace + "." + IntrinsicAssemblyTypeName;
internal const string GetExceptionMethodName = "GetException";
internal const string GetStowedExceptionMethodName = "GetStowedException";
internal const string GetObjectAtAddressMethodName = "GetObjectAtAddress";
internal const string GetReturnValueMethodName = "GetReturnValue";
internal const string CreateVariableMethodName = "CreateVariable";
internal const string GetVariableValueMethodName = "GetObjectByAlias";
internal const string GetVariableAddressMethodName = "GetVariableAddress";
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Portable/Symbols/SubstitutedEventSymbol.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedEventSymbol : WrappedEventSymbol
{
private readonly SubstitutedNamedTypeSymbol _containingType;
private TypeWithAnnotations.Boxed? _lazyType;
internal SubstitutedEventSymbol(SubstitutedNamedTypeSymbol containingType, EventSymbol originalDefinition)
: base(originalDefinition)
{
Debug.Assert(originalDefinition.IsDefinition);
_containingType = containingType;
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
if (_lazyType == null)
{
var type = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations);
Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null);
}
return _lazyType.Value;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override EventSymbol OriginalDefinition
{
get
{
return _underlyingEvent;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return OriginalDefinition.GetAttributes();
}
public override MethodSymbol? AddMethod
{
get
{
MethodSymbol? originalAddMethod = OriginalDefinition.AddMethod;
return (object?)originalAddMethod == null ? null : originalAddMethod.AsMember(_containingType);
}
}
public override MethodSymbol? RemoveMethod
{
get
{
MethodSymbol? originalRemoveMethod = OriginalDefinition.RemoveMethod;
return (object?)originalRemoveMethod == null ? null : originalRemoveMethod.AsMember(_containingType);
}
}
internal override FieldSymbol? AssociatedField
{
get
{
FieldSymbol? originalAssociatedField = OriginalDefinition.AssociatedField;
return (object?)originalAssociatedField == null ? null : originalAssociatedField.AsMember(_containingType);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return OriginalDefinition.IsExplicitInterfaceImplementation; }
}
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations;
private OverriddenOrHiddenMembersResult? _lazyOverriddenOrHiddenMembers;
public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution),
default(ImmutableArray<EventSymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
internal override bool MustCallMethodsDirectly
{
get { return OriginalDefinition.MustCallMethodsDirectly; }
}
internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
{
get
{
if (_lazyOverriddenOrHiddenMembers == null)
{
Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null);
}
return _lazyOverriddenOrHiddenMembers;
}
}
public override bool IsWindowsRuntimeEvent
{
get
{
// A substituted event computes overriding and interface implementation separately
// from the original definition, in case the type has changed. However, is should
// never be the case that providing type arguments changes a WinRT event to a
// non-WinRT event or vice versa, so we'll delegate to the original definition.
return OriginalDefinition.IsWindowsRuntimeEvent;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class SubstitutedEventSymbol : WrappedEventSymbol
{
private readonly SubstitutedNamedTypeSymbol _containingType;
private TypeWithAnnotations.Boxed? _lazyType;
internal SubstitutedEventSymbol(SubstitutedNamedTypeSymbol containingType, EventSymbol originalDefinition)
: base(originalDefinition)
{
Debug.Assert(originalDefinition.IsDefinition);
_containingType = containingType;
}
public override TypeWithAnnotations TypeWithAnnotations
{
get
{
if (_lazyType == null)
{
var type = _containingType.TypeSubstitution.SubstituteType(OriginalDefinition.TypeWithAnnotations);
Interlocked.CompareExchange(ref _lazyType, new TypeWithAnnotations.Boxed(type), null);
}
return _lazyType.Value;
}
}
public override Symbol ContainingSymbol
{
get
{
return _containingType;
}
}
public override EventSymbol OriginalDefinition
{
get
{
return _underlyingEvent;
}
}
public override ImmutableArray<CSharpAttributeData> GetAttributes()
{
return OriginalDefinition.GetAttributes();
}
public override MethodSymbol? AddMethod
{
get
{
MethodSymbol? originalAddMethod = OriginalDefinition.AddMethod;
return (object?)originalAddMethod == null ? null : originalAddMethod.AsMember(_containingType);
}
}
public override MethodSymbol? RemoveMethod
{
get
{
MethodSymbol? originalRemoveMethod = OriginalDefinition.RemoveMethod;
return (object?)originalRemoveMethod == null ? null : originalRemoveMethod.AsMember(_containingType);
}
}
internal override FieldSymbol? AssociatedField
{
get
{
FieldSymbol? originalAssociatedField = OriginalDefinition.AssociatedField;
return (object?)originalAssociatedField == null ? null : originalAssociatedField.AsMember(_containingType);
}
}
internal override bool IsExplicitInterfaceImplementation
{
get { return OriginalDefinition.IsExplicitInterfaceImplementation; }
}
//we want to compute this lazily since it may be expensive for the underlying symbol
private ImmutableArray<EventSymbol> _lazyExplicitInterfaceImplementations;
private OverriddenOrHiddenMembersResult? _lazyOverriddenOrHiddenMembers;
public override ImmutableArray<EventSymbol> ExplicitInterfaceImplementations
{
get
{
if (_lazyExplicitInterfaceImplementations.IsDefault)
{
ImmutableInterlocked.InterlockedCompareExchange(
ref _lazyExplicitInterfaceImplementations,
ExplicitInterfaceHelpers.SubstituteExplicitInterfaceImplementations(OriginalDefinition.ExplicitInterfaceImplementations, _containingType.TypeSubstitution),
default(ImmutableArray<EventSymbol>));
}
return _lazyExplicitInterfaceImplementations;
}
}
internal override bool MustCallMethodsDirectly
{
get { return OriginalDefinition.MustCallMethodsDirectly; }
}
internal override OverriddenOrHiddenMembersResult OverriddenOrHiddenMembers
{
get
{
if (_lazyOverriddenOrHiddenMembers == null)
{
Interlocked.CompareExchange(ref _lazyOverriddenOrHiddenMembers, this.MakeOverriddenOrHiddenMembers(), null);
}
return _lazyOverriddenOrHiddenMembers;
}
}
public override bool IsWindowsRuntimeEvent
{
get
{
// A substituted event computes overriding and interface implementation separately
// from the original definition, in case the type has changed. However, is should
// never be the case that providing type arguments changes a WinRT event to a
// non-WinRT event or vice versa, so we'll delegate to the original definition.
return OriginalDefinition.IsWindowsRuntimeEvent;
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/Core/Portable/ExtractMethod/IExtractMethodService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal interface IExtractMethodService : ILanguageService
{
Task<ExtractMethodResult> ExtractMethodAsync(Document document, TextSpan textSpan, bool localFunction, OptionSet options = null, CancellationToken cancellationToken = default);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
namespace Microsoft.CodeAnalysis.ExtractMethod
{
internal interface IExtractMethodService : ILanguageService
{
Task<ExtractMethodResult> ExtractMethodAsync(Document document, TextSpan textSpan, bool localFunction, OptionSet options = null, CancellationToken cancellationToken = default);
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/Core.Cocoa/CommandHandlers/GoToMatchingBraceCommandHandler.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommandHandlers
{
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(nameof(GoToMatchingBraceCommandHandler))]
internal class GoToMatchingBraceCommandHandler : VSCommanding.ICommandHandler<GotoBraceCommandArgs>
{
private readonly IBraceMatchingService _braceMatchingService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToMatchingBraceCommandHandler(IBraceMatchingService braceMatchingService)
{
_braceMatchingService = braceMatchingService ??
throw new ArgumentNullException(nameof(braceMatchingService));
}
public string DisplayName => nameof(GoToMatchingBraceCommandHandler);
public bool ExecuteCommand(GotoBraceCommandArgs args, VSCommanding.CommandExecutionContext executionContext)
{
var snapshot = args.SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
var caretPosition = args.TextView.Caret.Position.BufferPosition.Position;
var task = _braceMatchingService.FindMatchingSpanAsync(document, caretPosition, executionContext.OperationContext.UserCancellationToken);
var span = task.WaitAndGetResult(executionContext.OperationContext.UserCancellationToken);
if (!span.HasValue)
return false;
if (span.Value.Start < caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.Start));
else if (span.Value.End > caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.End));
return true;
}
public VSCommanding.CommandState GetCommandState(GotoBraceCommandArgs args)
{
return VSCommanding.CommandState.Available;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.Text.Shared.Extensions;
using Microsoft.VisualStudio.Text.Editor.Commanding.Commands;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
using VSCommanding = Microsoft.VisualStudio.Commanding;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CommandHandlers
{
[Export(typeof(VSCommanding.ICommandHandler))]
[ContentType(ContentTypeNames.RoslynContentType)]
[Name(nameof(GoToMatchingBraceCommandHandler))]
internal class GoToMatchingBraceCommandHandler : VSCommanding.ICommandHandler<GotoBraceCommandArgs>
{
private readonly IBraceMatchingService _braceMatchingService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public GoToMatchingBraceCommandHandler(IBraceMatchingService braceMatchingService)
{
_braceMatchingService = braceMatchingService ??
throw new ArgumentNullException(nameof(braceMatchingService));
}
public string DisplayName => nameof(GoToMatchingBraceCommandHandler);
public bool ExecuteCommand(GotoBraceCommandArgs args, VSCommanding.CommandExecutionContext executionContext)
{
var snapshot = args.SubjectBuffer.CurrentSnapshot;
var document = snapshot.GetOpenDocumentInCurrentContextWithChanges();
var caretPosition = args.TextView.Caret.Position.BufferPosition.Position;
var task = _braceMatchingService.FindMatchingSpanAsync(document, caretPosition, executionContext.OperationContext.UserCancellationToken);
var span = task.WaitAndGetResult(executionContext.OperationContext.UserCancellationToken);
if (!span.HasValue)
return false;
if (span.Value.Start < caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.Start));
else if (span.Value.End > caretPosition)
args.TextView.TryMoveCaretToAndEnsureVisible(args.SubjectBuffer.CurrentSnapshot.GetPoint(span.Value.End));
return true;
}
public VSCommanding.CommandState GetCommandState(GotoBraceCommandArgs args)
{
return VSCommanding.CommandState.Available;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Utilities/CompilerUtilities/ImmutableHashMapExtensions.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Roslyn.Collections.Immutable;
namespace Roslyn.Utilities
{
internal static class ImmutableHashMapExtensions
{
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key" /> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="valueProvider">The function to execute to obtain the value to insert into the dictionary if the key is not found. Returns null if the value can't be obtained.</param>
/// <param name="factoryArgument">The argument to pass to the value factory.</param>
/// <returns>The value obtained from the dictionary or <paramref name="valueProvider" /> if it was not present.</returns>
public static TValue? GetOrAdd<TKey, TValue, TArg>(ref ImmutableHashMap<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue?> valueProvider, TArg factoryArgument)
where TKey : notnull
where TValue : class
{
Contract.ThrowIfNull(valueProvider);
var map = Volatile.Read(ref location);
Contract.ThrowIfNull(map);
if (map.TryGetValue(key, out var existingValue))
{
return existingValue;
}
var newValue = valueProvider(key, factoryArgument);
if (newValue is null)
{
return null;
}
do
{
var augmentedMap = map.Add(key, newValue);
var replacedMap = Interlocked.CompareExchange(ref location, augmentedMap, map);
if (replacedMap == map)
{
return newValue;
}
map = replacedMap;
}
while (!map.TryGetValue(key, out existingValue));
return existingValue;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using Roslyn.Collections.Immutable;
namespace Roslyn.Utilities
{
internal static class ImmutableHashMapExtensions
{
/// <summary>
/// Obtains the value for the specified key from a dictionary, or adds a new value to the dictionary where the key did not previously exist.
/// </summary>
/// <typeparam name="TKey">The type of key stored by the dictionary.</typeparam>
/// <typeparam name="TValue">The type of value stored by the dictionary.</typeparam>
/// <typeparam name="TArg">The type of argument supplied to the value factory.</typeparam>
/// <param name="location">The variable or field to atomically update if the specified <paramref name="key" /> is not in the dictionary.</param>
/// <param name="key">The key for the value to retrieve or add.</param>
/// <param name="valueProvider">The function to execute to obtain the value to insert into the dictionary if the key is not found. Returns null if the value can't be obtained.</param>
/// <param name="factoryArgument">The argument to pass to the value factory.</param>
/// <returns>The value obtained from the dictionary or <paramref name="valueProvider" /> if it was not present.</returns>
public static TValue? GetOrAdd<TKey, TValue, TArg>(ref ImmutableHashMap<TKey, TValue> location, TKey key, Func<TKey, TArg, TValue?> valueProvider, TArg factoryArgument)
where TKey : notnull
where TValue : class
{
Contract.ThrowIfNull(valueProvider);
var map = Volatile.Read(ref location);
Contract.ThrowIfNull(map);
if (map.TryGetValue(key, out var existingValue))
{
return existingValue;
}
var newValue = valueProvider(key, factoryArgument);
if (newValue is null)
{
return null;
}
do
{
var augmentedMap = map.Add(key, newValue);
var replacedMap = Interlocked.CompareExchange(ref location, augmentedMap, map);
if (replacedMap == map)
{
return newValue;
}
map = replacedMap;
}
while (!map.TryGetValue(key, out existingValue));
return existingValue;
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/CSharp/Portable/Simplification/Simplifiers/NameSimplifier.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
internal class NameSimplifier : AbstractCSharpSimplifier<NameSyntax, TypeSyntax>
{
public static readonly NameSimplifier Instance = new();
private NameSimplifier()
{
}
public override bool TrySimplify(
NameSyntax name,
SemanticModel semanticModel,
OptionSet optionSet,
out TypeSyntax replacementNode,
out TextSpan issueSpan,
CancellationToken cancellationToken)
{
replacementNode = null;
issueSpan = default;
if (name.IsVar)
{
return false;
}
// we should not simplify a name of a namespace declaration
if (IsPartOfNamespaceDeclarationName(name))
{
return false;
}
// We can simplify Qualified names and AliasQualifiedNames. Generally, if we have
// something like "A.B.C.D", we only consider the full thing something we can simplify.
// However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the
// first open name. This is because if we remove the open name, we'll often change
// meaning as "D" will bind to C<T>.D which is different than C<>.D!
if (name is QualifiedNameSyntax qualifiedName)
{
var left = qualifiedName.Left;
if (ContainsOpenName(left))
{
// Don't simplify A.B<>.C
return false;
}
}
// 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and
// nothing we can do here.
var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name);
if (symbol == null)
{
return false;
}
// treat constructor names as types
var method = symbol as IMethodSymbol;
if (method.IsConstructor())
{
symbol = method.ContainingType;
}
if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName)
{
var genericName = (GenericNameSyntax)name;
replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier)
.WithLeadingTrivia(genericName.GetLeadingTrivia())
.WithTrailingTrivia(genericName.GetTrailingTrivia());
issueSpan = genericName.TypeArgumentList.Span;
return CanReplaceWithReducedName(
name, replacementNode, semanticModel, cancellationToken);
}
if (!(symbol is INamespaceOrTypeSymbol))
{
return false;
}
if (name.HasAnnotations(SpecialTypeAnnotation.Kind))
{
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
name.GetLeadingTrivia(),
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
name.GetTrailingTrivia()));
issueSpan = name.Span;
return CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
}
else
{
if (!name.IsRightSideOfDotOrColonColon())
{
if (TryReplaceExpressionWithAlias(name, semanticModel, symbol, cancellationToken, out var aliasReplacement))
{
// get the token text as it appears in source code to preserve e.g. Unicode character escaping
var text = aliasReplacement.Name;
var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault();
if (syntaxRef != null)
{
var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier;
text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString();
}
var identifierToken = SyntaxFactory.Identifier(
name.GetLeadingTrivia(),
SyntaxKind.IdentifierToken,
text,
aliasReplacement.Name,
name.GetTrailingTrivia());
identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name);
replacementNode = SyntaxFactory.IdentifierName(identifierToken);
// Merge annotation to new syntax node
var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken);
issueSpan = name.Span;
// In case the alias name is the same as the last name of the alias target, we only include
// the left part of the name in the unnecessary span to Not confuse uses.
if (name.Kind() == SyntaxKind.QualifiedName)
{
var qualifiedName3 = (QualifiedNameSyntax)name;
if (qualifiedName3.Right.Identifier.ValueText == identifierToken.ValueText)
{
issueSpan = qualifiedName3.Left.Span;
}
}
// first check if this would be a valid reduction
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
// in case this alias name ends with "Attribute", we're going to see if we can also
// remove that suffix.
if (TryReduceAttributeSuffix(
name,
identifierToken,
out var replacementNodeWithoutAttributeSuffix,
out var issueSpanWithoutAttributeSuffix))
{
if (CanReplaceWithReducedName(name, replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken))
{
replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix);
issueSpan = issueSpanWithoutAttributeSuffix;
}
}
return true;
}
return false;
}
var nameHasNoAlias = false;
if (name is SimpleNameSyntax simpleName)
{
if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind))
{
nameHasNoAlias = true;
}
}
if (name is QualifiedNameSyntax qualifiedName2)
{
if (!qualifiedName2.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
if (name is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Name is SimpleNameSyntax &&
!aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) &&
!aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken);
if (nameHasNoAlias && aliasInfo == null)
{
// Don't simplify to predefined type if name is part of a QualifiedName.
// QualifiedNames can't contain PredefinedTypeNames (although MemberAccessExpressions can).
// In other words, the left side of a QualifiedName can't be a PredefinedTypeName.
var inDeclarationContext = PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel);
var inMemberAccessContext = PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel);
if (!name.Parent.IsKind(SyntaxKind.QualifiedName) && (inDeclarationContext || inMemberAccessContext))
{
// See if we can simplify this name (like System.Int32) to a built-in type (like 'int').
// If not, we'll still fall through and see if we can convert it to Int32.
var codeStyleOptionName = inDeclarationContext
? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
: nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess);
var type = semanticModel.GetTypeInfo(name, cancellationToken).Type;
if (type != null)
{
var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
else
{
var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol;
if (typeSymbol.IsKind(SymbolKind.NamedType))
{
var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
}
}
}
// Nullable rewrite: Nullable<int> -> int?
// Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something
if (!name.IsVar && symbol.Kind == SymbolKind.NamedType && !name.IsLeftSideOfQualifiedName())
{
var type = (INamedTypeSymbol)symbol;
if (aliasInfo == null && CanSimplifyNullable(type, name, semanticModel))
{
GenericNameSyntax genericName;
if (name.Kind() == SyntaxKind.QualifiedName)
{
genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right;
}
else
{
genericName = (GenericNameSyntax)name;
}
var oldType = genericName.TypeArgumentList.Arguments.First();
if (oldType.Kind() == SyntaxKind.OmittedTypeArgument)
{
return false;
}
replacementNode = SyntaxFactory.NullableType(oldType)
.WithLeadingTrivia(name.GetLeadingTrivia())
.WithTrailingTrivia(name.GetTrailingTrivia());
issueSpan = name.Span;
// we need to simplify the whole qualified name at once, because replacing the identifier on the left in
// System.Nullable<int> alone would be illegal.
// If this fails we want to continue to try at least to remove the System if possible.
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
return true;
}
}
}
}
SyntaxToken identifier;
switch (name.Kind())
{
case SyntaxKind.AliasQualifiedName:
var simpleName = ((AliasQualifiedNameSyntax)name).Name
.WithLeadingTrivia(name.GetLeadingTrivia());
simpleName = simpleName.ReplaceToken(simpleName.Identifier,
((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo(
simpleName.Identifier.WithLeadingTrivia(
((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia)));
replacementNode = simpleName;
issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span;
break;
case SyntaxKind.QualifiedName:
replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = ((QualifiedNameSyntax)name).Left.Span;
break;
case SyntaxKind.IdentifierName:
identifier = ((IdentifierNameSyntax)name).Identifier;
// we can try to remove the Attribute suffix if this is the attribute name
TryReduceAttributeSuffix(name, identifier, out replacementNode, out issueSpan);
break;
}
}
if (replacementNode == null)
{
return false;
}
// We may be looking at a name `X.Y` seeing if we can replace it with `Y`. However, in
// order to know for sure, we actually have to look slightly higher at `X.Y.Z` to see if
// it can simplify to `Y.Z`. This is because in the `Color Color` case we can only tell
// if we can reduce by looking by also looking at what comes next to see if it will
// cause the simplified name to bind to the instance or static side.
if (TryReduceCrefColorColor(name, replacementNode, semanticModel, cancellationToken))
{
return true;
}
return CanReplaceWithReducedName(name, replacementNode, semanticModel, cancellationToken);
}
private static bool TryReduceCrefColorColor(
NameSyntax name, TypeSyntax replacement,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!name.InsideCrefReference())
return false;
if (name.Parent is QualifiedCrefSyntax qualifiedCrefParent && qualifiedCrefParent.Container == name)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a
// QualifiedCrefSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member);
if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken))
return true;
}
else if (name.Parent is QualifiedNameSyntax qualifiedParent && qualifiedParent.Left == name &&
replacement is NameSyntax replacementName)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B with B. In this case the parent of A.B is A.B.C which is a
// QualifiedNameSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right);
return CanReplaceWithReducedName(
qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken);
}
return false;
}
private static bool CanSimplifyNullable(INamedTypeSymbol type, NameSyntax name, SemanticModel semanticModel)
{
if (!type.IsNullable())
{
return false;
}
if (type.IsUnboundGenericType)
{
// Don't simplify unbound generic type "Nullable<>".
return false;
}
if (InsideNameOfExpression(name, semanticModel))
{
// Nullable<T> can't be simplified to T? in nameof expressions.
return false;
}
if (!name.InsideCrefReference())
{
// Nullable<T> can always be simplified to T? outside crefs.
return true;
}
if (name.Parent is NameMemberCrefSyntax)
return false;
// Inside crefs, if the T in this Nullable{T} is being declared right here
// then this Nullable{T} is not a constructed generic type and we should
// not offer to simplify this to T?.
//
// For example, we should not offer the simplification in the following cases where
// T does not bind to an existing type / type parameter in the user's code.
// - <see cref="Nullable{T}"/>
// - <see cref="System.Nullable{T}.Value"/>
//
// And we should offer the simplification in the following cases where SomeType and
// SomeMethod bind to a type and method declared elsewhere in the users code.
// - <see cref="SomeType.SomeMethod(Nullable{SomeType})"/>
var argument = type.TypeArguments.SingleOrDefault();
if (argument == null || argument.IsErrorType())
{
return false;
}
var argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault();
if (argumentDecl == null)
{
// The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)).
return true;
}
return !name.Span.Contains(argumentDecl.Span);
}
private static bool CanReplaceWithPredefinedTypeKeywordInContext(
NameSyntax name,
SemanticModel semanticModel,
out TypeSyntax replacementNode,
ref TextSpan issueSpan,
SyntaxKind keywordKind,
string codeStyleOptionName)
{
replacementNode = CreatePredefinedTypeSyntax(name, keywordKind);
issueSpan = name.Span; // we want to show the whole name expression as unnecessary
var canReduce = CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
if (canReduce)
{
replacementNode = replacementNode.WithAdditionalAnnotations(new SyntaxAnnotation(codeStyleOptionName));
}
return canReduce;
}
private static bool TryReduceAttributeSuffix(
NameSyntax name,
SyntaxToken identifierToken,
out TypeSyntax replacementNode,
out TextSpan issueSpan)
{
issueSpan = default;
replacementNode = null;
// we can try to remove the Attribute suffix if this is the attribute name
if (SyntaxFacts.IsAttributeName(name))
{
if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon())
{
const string AttributeName = "Attribute";
// an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName, StringComparison.Ordinal) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
{
// weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code.
// so we need another check for keywords manually.
var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9);
if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None)
{
return false;
}
// if this attribute name in source contained Unicode escaping, we will loose it now
// because there is no easy way to determine the substring from identifier->ToString()
// which would be needed to pass to SyntaxFactory.Identifier
// The result is an unescaped Unicode character in source.
// once we remove the Attribute suffix, we can't use an escaped identifier
var newIdentifierToken = identifierToken.CopyAnnotationsTo(
SyntaxFactory.Identifier(
identifierToken.LeadingTrivia,
newAttributeName,
identifierToken.TrailingTrivia));
replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken)
.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = new TextSpan(identifierToken.Span.End - 9, 9);
return true;
}
}
}
return false;
}
/// <summary>
/// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
/// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
/// property.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static bool IsPartOfNamespaceDeclarationName(SyntaxNode node)
{
var parent = node;
while (parent != null)
{
switch (parent.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
node = parent;
parent = parent.Parent;
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent;
return object.Equals(namespaceDeclaration.Name, node);
default:
return false;
}
}
return false;
}
public static bool CanReplaceWithReducedNameInContext(
NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel)
{
// Check for certain things that would prevent us from reducing this name in this context.
// For example, you can simplify "using a = System.Int32" to "using a = int" as it's simply
// not allowed in the C# grammar.
if (IsNonNameSyntaxInUsingDirective(name, reducedName) ||
WillConflictWithExistingLocal(name, reducedName, semanticModel) ||
IsAmbiguousCast(name, reducedName) ||
IsNullableTypeInPointerExpression(reducedName) ||
IsNotNullableReplaceable(name, reducedName) ||
IsNonReducableQualifiedNameInUsingDirective(semanticModel, name))
{
return false;
}
return true;
}
private static bool ContainsOpenName(NameSyntax name)
{
if (name is QualifiedNameSyntax qualifiedName)
{
return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right);
}
else if (name is GenericNameSyntax genericName)
{
return genericName.IsUnboundGenericName;
}
else
{
return false;
}
}
private static bool CanReplaceWithReducedName(NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken);
if (speculationAnalyzer.ReplacementChangesSemantics())
{
return false;
}
return NameSimplifier.CanReplaceWithReducedNameInContext(name, reducedName, semanticModel);
}
private static bool IsNotNullableReplaceable(NameSyntax name, TypeSyntax reducedName)
{
if (reducedName.IsKind(SyntaxKind.NullableType, out NullableTypeSyntax nullableType))
{
if (nullableType.ElementType.Kind() == SyntaxKind.OmittedTypeArgument)
return true;
return name.IsLeftSideOfDot() || name.IsRightSideOfDot();
}
return false;
}
private static bool IsNullableTypeInPointerExpression(ExpressionSyntax simplifiedNode)
{
// Note: nullable type syntax is not allowed in pointer type syntax
if (simplifiedNode.Kind() == SyntaxKind.NullableType &&
simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax))
{
return true;
}
return false;
}
private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
return
expression.IsParentKind(SyntaxKind.UsingDirective) &&
!(simplifiedNode is NameSyntax);
}
private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
// Can't simplify a type name in a cast expression if it would then cause the cast to be
// parsed differently. For example: (Goo::Bar)+1 is a cast. But if that simplifies to
// (Bar)+1 then that's an arithmetic expression.
if (expression.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) &&
castExpression.Type == expression)
{
var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode);
var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString());
if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression))
{
return true;
}
}
return false;
}
private static bool IsNonReducableQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
// Whereas most of the time we do not want to reduce namespace names, We will
// make an exception for namespaces with the global:: alias.
return IsQualifiedNameInUsingDirective(model, name) &&
!IsGlobalAliasQualifiedName(name);
}
private static bool IsQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
while (name.IsLeftSideOfQualifiedName())
{
name = (NameSyntax)name.Parent;
}
if (name.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax usingDirective) &&
usingDirective.Alias == null)
{
// We're a qualified name in a using. We don't want to reduce this name as people like
// fully qualified names in usings so they can properly tell what the name is resolving
// to.
// However, if this name is actually referencing the special Script class, then we do
// want to allow that to be reduced.
return !IsInScriptClass(model, name);
}
return false;
}
private static bool IsGlobalAliasQualifiedName(NameSyntax name)
{
// Checks whether the `global::` alias is applied to the name
return name is AliasQualifiedNameSyntax aliasName &&
aliasName.Alias.Identifier.IsKind(SyntaxKind.GlobalKeyword);
}
private static bool IsInScriptClass(SemanticModel model, NameSyntax name)
{
var symbol = model.GetSymbolInfo(name).Symbol as INamedTypeSymbol;
while (symbol != null)
{
if (symbol.IsScriptClass)
{
return true;
}
symbol = symbol.ContainingType;
}
return false;
}
private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel)
{
return !name.IsDirectChildOfMemberAccessExpression() &&
!name.InsideCrefReference() &&
!InsideNameOfExpression(name, semanticModel) &&
SimplificationHelpers.PreferPredefinedTypeKeywordInDeclarations(optionSet, semanticModel.Language);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Utilities;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Simplification.Simplifiers
{
using Microsoft.CodeAnalysis.Rename.ConflictEngine;
internal class NameSimplifier : AbstractCSharpSimplifier<NameSyntax, TypeSyntax>
{
public static readonly NameSimplifier Instance = new();
private NameSimplifier()
{
}
public override bool TrySimplify(
NameSyntax name,
SemanticModel semanticModel,
OptionSet optionSet,
out TypeSyntax replacementNode,
out TextSpan issueSpan,
CancellationToken cancellationToken)
{
replacementNode = null;
issueSpan = default;
if (name.IsVar)
{
return false;
}
// we should not simplify a name of a namespace declaration
if (IsPartOfNamespaceDeclarationName(name))
{
return false;
}
// We can simplify Qualified names and AliasQualifiedNames. Generally, if we have
// something like "A.B.C.D", we only consider the full thing something we can simplify.
// However, in the case of "A.B.C<>.D", then we'll only consider simplifying up to the
// first open name. This is because if we remove the open name, we'll often change
// meaning as "D" will bind to C<T>.D which is different than C<>.D!
if (name is QualifiedNameSyntax qualifiedName)
{
var left = qualifiedName.Left;
if (ContainsOpenName(left))
{
// Don't simplify A.B<>.C
return false;
}
}
// 1. see whether binding the name binds to a symbol/type. if not, it is ambiguous and
// nothing we can do here.
var symbol = SimplificationHelpers.GetOriginalSymbolInfo(semanticModel, name);
if (symbol == null)
{
return false;
}
// treat constructor names as types
var method = symbol as IMethodSymbol;
if (method.IsConstructor())
{
symbol = method.ContainingType;
}
if (symbol.Kind == SymbolKind.Method && name.Kind() == SyntaxKind.GenericName)
{
var genericName = (GenericNameSyntax)name;
replacementNode = SyntaxFactory.IdentifierName(genericName.Identifier)
.WithLeadingTrivia(genericName.GetLeadingTrivia())
.WithTrailingTrivia(genericName.GetTrailingTrivia());
issueSpan = genericName.TypeArgumentList.Span;
return CanReplaceWithReducedName(
name, replacementNode, semanticModel, cancellationToken);
}
if (!(symbol is INamespaceOrTypeSymbol))
{
return false;
}
if (name.HasAnnotations(SpecialTypeAnnotation.Kind))
{
replacementNode = SyntaxFactory.PredefinedType(
SyntaxFactory.Token(
name.GetLeadingTrivia(),
GetPredefinedKeywordKind(SpecialTypeAnnotation.GetSpecialType(name.GetAnnotations(SpecialTypeAnnotation.Kind).First())),
name.GetTrailingTrivia()));
issueSpan = name.Span;
return CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
}
else
{
if (!name.IsRightSideOfDotOrColonColon())
{
if (TryReplaceExpressionWithAlias(name, semanticModel, symbol, cancellationToken, out var aliasReplacement))
{
// get the token text as it appears in source code to preserve e.g. Unicode character escaping
var text = aliasReplacement.Name;
var syntaxRef = aliasReplacement.DeclaringSyntaxReferences.FirstOrDefault();
if (syntaxRef != null)
{
var declIdentifier = ((UsingDirectiveSyntax)syntaxRef.GetSyntax(cancellationToken)).Alias.Name.Identifier;
text = declIdentifier.IsVerbatimIdentifier() ? declIdentifier.ToString().Substring(1) : declIdentifier.ToString();
}
var identifierToken = SyntaxFactory.Identifier(
name.GetLeadingTrivia(),
SyntaxKind.IdentifierToken,
text,
aliasReplacement.Name,
name.GetTrailingTrivia());
identifierToken = CSharpSimplificationService.TryEscapeIdentifierToken(identifierToken, name);
replacementNode = SyntaxFactory.IdentifierName(identifierToken);
// Merge annotation to new syntax node
var annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(RenameAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
annotatedNodesOrTokens = name.GetAnnotatedNodesAndTokens(AliasAnnotation.Kind);
foreach (var annotatedNodeOrToken in annotatedNodesOrTokens)
{
if (annotatedNodeOrToken.IsToken)
{
identifierToken = annotatedNodeOrToken.AsToken().CopyAnnotationsTo(identifierToken);
}
else
{
replacementNode = annotatedNodeOrToken.AsNode().CopyAnnotationsTo(replacementNode);
}
}
replacementNode = ((SimpleNameSyntax)replacementNode).WithIdentifier(identifierToken);
issueSpan = name.Span;
// In case the alias name is the same as the last name of the alias target, we only include
// the left part of the name in the unnecessary span to Not confuse uses.
if (name.Kind() == SyntaxKind.QualifiedName)
{
var qualifiedName3 = (QualifiedNameSyntax)name;
if (qualifiedName3.Right.Identifier.ValueText == identifierToken.ValueText)
{
issueSpan = qualifiedName3.Left.Span;
}
}
// first check if this would be a valid reduction
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
// in case this alias name ends with "Attribute", we're going to see if we can also
// remove that suffix.
if (TryReduceAttributeSuffix(
name,
identifierToken,
out var replacementNodeWithoutAttributeSuffix,
out var issueSpanWithoutAttributeSuffix))
{
if (CanReplaceWithReducedName(name, replacementNodeWithoutAttributeSuffix, semanticModel, cancellationToken))
{
replacementNode = replacementNode.CopyAnnotationsTo(replacementNodeWithoutAttributeSuffix);
issueSpan = issueSpanWithoutAttributeSuffix;
}
}
return true;
}
return false;
}
var nameHasNoAlias = false;
if (name is SimpleNameSyntax simpleName)
{
if (!simpleName.Identifier.HasAnnotations(AliasAnnotation.Kind))
{
nameHasNoAlias = true;
}
}
if (name is QualifiedNameSyntax qualifiedName2)
{
if (!qualifiedName2.Right.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
if (name is AliasQualifiedNameSyntax aliasQualifiedName)
{
if (aliasQualifiedName.Name is SimpleNameSyntax &&
!aliasQualifiedName.Name.Identifier.HasAnnotations(AliasAnnotation.Kind) &&
!aliasQualifiedName.Name.HasAnnotation(Simplifier.SpecialTypeAnnotation))
{
nameHasNoAlias = true;
}
}
var aliasInfo = semanticModel.GetAliasInfo(name, cancellationToken);
if (nameHasNoAlias && aliasInfo == null)
{
// Don't simplify to predefined type if name is part of a QualifiedName.
// QualifiedNames can't contain PredefinedTypeNames (although MemberAccessExpressions can).
// In other words, the left side of a QualifiedName can't be a PredefinedTypeName.
var inDeclarationContext = PreferPredefinedTypeKeywordInDeclarations(name, optionSet, semanticModel);
var inMemberAccessContext = PreferPredefinedTypeKeywordInMemberAccess(name, optionSet, semanticModel);
if (!name.Parent.IsKind(SyntaxKind.QualifiedName) && (inDeclarationContext || inMemberAccessContext))
{
// See if we can simplify this name (like System.Int32) to a built-in type (like 'int').
// If not, we'll still fall through and see if we can convert it to Int32.
var codeStyleOptionName = inDeclarationContext
? nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInDeclaration)
: nameof(CodeStyleOptions2.PreferIntrinsicPredefinedTypeKeywordInMemberAccess);
var type = semanticModel.GetTypeInfo(name, cancellationToken).Type;
if (type != null)
{
var keywordKind = GetPredefinedKeywordKind(type.SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
else
{
var typeSymbol = semanticModel.GetSymbolInfo(name, cancellationToken).Symbol;
if (typeSymbol.IsKind(SymbolKind.NamedType))
{
var keywordKind = GetPredefinedKeywordKind(((INamedTypeSymbol)typeSymbol).SpecialType);
if (keywordKind != SyntaxKind.None &&
CanReplaceWithPredefinedTypeKeywordInContext(name, semanticModel, out replacementNode, ref issueSpan, keywordKind, codeStyleOptionName))
{
return true;
}
}
}
}
}
// Nullable rewrite: Nullable<int> -> int?
// Don't rewrite in the case where Nullable<int> is part of some qualified name like Nullable<int>.Something
if (!name.IsVar && symbol.Kind == SymbolKind.NamedType && !name.IsLeftSideOfQualifiedName())
{
var type = (INamedTypeSymbol)symbol;
if (aliasInfo == null && CanSimplifyNullable(type, name, semanticModel))
{
GenericNameSyntax genericName;
if (name.Kind() == SyntaxKind.QualifiedName)
{
genericName = (GenericNameSyntax)((QualifiedNameSyntax)name).Right;
}
else
{
genericName = (GenericNameSyntax)name;
}
var oldType = genericName.TypeArgumentList.Arguments.First();
if (oldType.Kind() == SyntaxKind.OmittedTypeArgument)
{
return false;
}
replacementNode = SyntaxFactory.NullableType(oldType)
.WithLeadingTrivia(name.GetLeadingTrivia())
.WithTrailingTrivia(name.GetTrailingTrivia());
issueSpan = name.Span;
// we need to simplify the whole qualified name at once, because replacing the identifier on the left in
// System.Nullable<int> alone would be illegal.
// If this fails we want to continue to try at least to remove the System if possible.
if (CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel))
{
return true;
}
}
}
}
SyntaxToken identifier;
switch (name.Kind())
{
case SyntaxKind.AliasQualifiedName:
var simpleName = ((AliasQualifiedNameSyntax)name).Name
.WithLeadingTrivia(name.GetLeadingTrivia());
simpleName = simpleName.ReplaceToken(simpleName.Identifier,
((AliasQualifiedNameSyntax)name).Name.Identifier.CopyAnnotationsTo(
simpleName.Identifier.WithLeadingTrivia(
((AliasQualifiedNameSyntax)name).Alias.Identifier.LeadingTrivia)));
replacementNode = simpleName;
issueSpan = ((AliasQualifiedNameSyntax)name).Alias.Span;
break;
case SyntaxKind.QualifiedName:
replacementNode = ((QualifiedNameSyntax)name).Right.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = ((QualifiedNameSyntax)name).Left.Span;
break;
case SyntaxKind.IdentifierName:
identifier = ((IdentifierNameSyntax)name).Identifier;
// we can try to remove the Attribute suffix if this is the attribute name
TryReduceAttributeSuffix(name, identifier, out replacementNode, out issueSpan);
break;
}
}
if (replacementNode == null)
{
return false;
}
// We may be looking at a name `X.Y` seeing if we can replace it with `Y`. However, in
// order to know for sure, we actually have to look slightly higher at `X.Y.Z` to see if
// it can simplify to `Y.Z`. This is because in the `Color Color` case we can only tell
// if we can reduce by looking by also looking at what comes next to see if it will
// cause the simplified name to bind to the instance or static side.
if (TryReduceCrefColorColor(name, replacementNode, semanticModel, cancellationToken))
{
return true;
}
return CanReplaceWithReducedName(name, replacementNode, semanticModel, cancellationToken);
}
private static bool TryReduceCrefColorColor(
NameSyntax name, TypeSyntax replacement,
SemanticModel semanticModel, CancellationToken cancellationToken)
{
if (!name.InsideCrefReference())
return false;
if (name.Parent is QualifiedCrefSyntax qualifiedCrefParent && qualifiedCrefParent.Container == name)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B.C with C. In this case the parent of A.B.C is A.B.C.D which is a
// QualifiedCrefSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedCref(replacement, qualifiedCrefParent.Member);
if (QualifiedCrefSimplifier.CanSimplifyWithReplacement(qualifiedCrefParent, semanticModel, qualifiedReplacement, cancellationToken))
return true;
}
else if (name.Parent is QualifiedNameSyntax qualifiedParent && qualifiedParent.Left == name &&
replacement is NameSyntax replacementName)
{
// we have <see cref="A.B.C.D"/> and we're trying to see if we can replace
// A.B with B. In this case the parent of A.B is A.B.C which is a
// QualifiedNameSyntax
var qualifiedReplacement = SyntaxFactory.QualifiedName(replacementName, qualifiedParent.Right);
return CanReplaceWithReducedName(
qualifiedParent, qualifiedReplacement, semanticModel, cancellationToken);
}
return false;
}
private static bool CanSimplifyNullable(INamedTypeSymbol type, NameSyntax name, SemanticModel semanticModel)
{
if (!type.IsNullable())
{
return false;
}
if (type.IsUnboundGenericType)
{
// Don't simplify unbound generic type "Nullable<>".
return false;
}
if (InsideNameOfExpression(name, semanticModel))
{
// Nullable<T> can't be simplified to T? in nameof expressions.
return false;
}
if (!name.InsideCrefReference())
{
// Nullable<T> can always be simplified to T? outside crefs.
return true;
}
if (name.Parent is NameMemberCrefSyntax)
return false;
// Inside crefs, if the T in this Nullable{T} is being declared right here
// then this Nullable{T} is not a constructed generic type and we should
// not offer to simplify this to T?.
//
// For example, we should not offer the simplification in the following cases where
// T does not bind to an existing type / type parameter in the user's code.
// - <see cref="Nullable{T}"/>
// - <see cref="System.Nullable{T}.Value"/>
//
// And we should offer the simplification in the following cases where SomeType and
// SomeMethod bind to a type and method declared elsewhere in the users code.
// - <see cref="SomeType.SomeMethod(Nullable{SomeType})"/>
var argument = type.TypeArguments.SingleOrDefault();
if (argument == null || argument.IsErrorType())
{
return false;
}
var argumentDecl = argument.DeclaringSyntaxReferences.FirstOrDefault();
if (argumentDecl == null)
{
// The type argument is a type from metadata - so this is a constructed generic nullable type that can be simplified (e.g. Nullable(Of Integer)).
return true;
}
return !name.Span.Contains(argumentDecl.Span);
}
private static bool CanReplaceWithPredefinedTypeKeywordInContext(
NameSyntax name,
SemanticModel semanticModel,
out TypeSyntax replacementNode,
ref TextSpan issueSpan,
SyntaxKind keywordKind,
string codeStyleOptionName)
{
replacementNode = CreatePredefinedTypeSyntax(name, keywordKind);
issueSpan = name.Span; // we want to show the whole name expression as unnecessary
var canReduce = CanReplaceWithReducedNameInContext(name, replacementNode, semanticModel);
if (canReduce)
{
replacementNode = replacementNode.WithAdditionalAnnotations(new SyntaxAnnotation(codeStyleOptionName));
}
return canReduce;
}
private static bool TryReduceAttributeSuffix(
NameSyntax name,
SyntaxToken identifierToken,
out TypeSyntax replacementNode,
out TextSpan issueSpan)
{
issueSpan = default;
replacementNode = null;
// we can try to remove the Attribute suffix if this is the attribute name
if (SyntaxFacts.IsAttributeName(name))
{
if (name.Parent.Kind() == SyntaxKind.Attribute || name.IsRightSideOfDotOrColonColon())
{
const string AttributeName = "Attribute";
// an attribute that should keep it (unnecessary "Attribute" suffix should be annotated with a DontSimplifyAnnotation
if (identifierToken.ValueText != AttributeName && identifierToken.ValueText.EndsWith(AttributeName, StringComparison.Ordinal) && !identifierToken.HasAnnotation(SimplificationHelpers.DontSimplifyAnnotation))
{
// weird. the semantic model is able to bind attribute syntax like "[as()]" although it's not valid code.
// so we need another check for keywords manually.
var newAttributeName = identifierToken.ValueText.Substring(0, identifierToken.ValueText.Length - 9);
if (SyntaxFacts.GetKeywordKind(newAttributeName) != SyntaxKind.None)
{
return false;
}
// if this attribute name in source contained Unicode escaping, we will loose it now
// because there is no easy way to determine the substring from identifier->ToString()
// which would be needed to pass to SyntaxFactory.Identifier
// The result is an unescaped Unicode character in source.
// once we remove the Attribute suffix, we can't use an escaped identifier
var newIdentifierToken = identifierToken.CopyAnnotationsTo(
SyntaxFactory.Identifier(
identifierToken.LeadingTrivia,
newAttributeName,
identifierToken.TrailingTrivia));
replacementNode = SyntaxFactory.IdentifierName(newIdentifierToken)
.WithLeadingTrivia(name.GetLeadingTrivia());
issueSpan = new TextSpan(identifierToken.Span.End - 9, 9);
return true;
}
}
}
return false;
}
/// <summary>
/// Checks if the SyntaxNode is a name of a namespace declaration. To be a namespace name, the syntax
/// must be parented by an namespace declaration and the node itself must be equal to the declaration's Name
/// property.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private static bool IsPartOfNamespaceDeclarationName(SyntaxNode node)
{
var parent = node;
while (parent != null)
{
switch (parent.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.QualifiedName:
node = parent;
parent = parent.Parent;
break;
case SyntaxKind.NamespaceDeclaration:
case SyntaxKind.FileScopedNamespaceDeclaration:
var namespaceDeclaration = (BaseNamespaceDeclarationSyntax)parent;
return object.Equals(namespaceDeclaration.Name, node);
default:
return false;
}
}
return false;
}
public static bool CanReplaceWithReducedNameInContext(
NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel)
{
// Check for certain things that would prevent us from reducing this name in this context.
// For example, you can simplify "using a = System.Int32" to "using a = int" as it's simply
// not allowed in the C# grammar.
if (IsNonNameSyntaxInUsingDirective(name, reducedName) ||
WillConflictWithExistingLocal(name, reducedName, semanticModel) ||
IsAmbiguousCast(name, reducedName) ||
IsNullableTypeInPointerExpression(reducedName) ||
IsNotNullableReplaceable(name, reducedName) ||
IsNonReducableQualifiedNameInUsingDirective(semanticModel, name))
{
return false;
}
return true;
}
private static bool ContainsOpenName(NameSyntax name)
{
if (name is QualifiedNameSyntax qualifiedName)
{
return ContainsOpenName(qualifiedName.Left) || ContainsOpenName(qualifiedName.Right);
}
else if (name is GenericNameSyntax genericName)
{
return genericName.IsUnboundGenericName;
}
else
{
return false;
}
}
private static bool CanReplaceWithReducedName(NameSyntax name, TypeSyntax reducedName, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var speculationAnalyzer = new SpeculationAnalyzer(name, reducedName, semanticModel, cancellationToken);
if (speculationAnalyzer.ReplacementChangesSemantics())
{
return false;
}
return NameSimplifier.CanReplaceWithReducedNameInContext(name, reducedName, semanticModel);
}
private static bool IsNotNullableReplaceable(NameSyntax name, TypeSyntax reducedName)
{
if (reducedName.IsKind(SyntaxKind.NullableType, out NullableTypeSyntax nullableType))
{
if (nullableType.ElementType.Kind() == SyntaxKind.OmittedTypeArgument)
return true;
return name.IsLeftSideOfDot() || name.IsRightSideOfDot();
}
return false;
}
private static bool IsNullableTypeInPointerExpression(ExpressionSyntax simplifiedNode)
{
// Note: nullable type syntax is not allowed in pointer type syntax
if (simplifiedNode.Kind() == SyntaxKind.NullableType &&
simplifiedNode.DescendantNodes().Any(n => n is PointerTypeSyntax))
{
return true;
}
return false;
}
private static bool IsNonNameSyntaxInUsingDirective(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
return
expression.IsParentKind(SyntaxKind.UsingDirective) &&
!(simplifiedNode is NameSyntax);
}
private static bool IsAmbiguousCast(ExpressionSyntax expression, ExpressionSyntax simplifiedNode)
{
// Can't simplify a type name in a cast expression if it would then cause the cast to be
// parsed differently. For example: (Goo::Bar)+1 is a cast. But if that simplifies to
// (Bar)+1 then that's an arithmetic expression.
if (expression.IsParentKind(SyntaxKind.CastExpression, out CastExpressionSyntax castExpression) &&
castExpression.Type == expression)
{
var newCastExpression = castExpression.ReplaceNode(castExpression.Type, simplifiedNode);
var reparsedCastExpression = SyntaxFactory.ParseExpression(newCastExpression.ToString());
if (!reparsedCastExpression.IsKind(SyntaxKind.CastExpression))
{
return true;
}
}
return false;
}
private static bool IsNonReducableQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
// Whereas most of the time we do not want to reduce namespace names, We will
// make an exception for namespaces with the global:: alias.
return IsQualifiedNameInUsingDirective(model, name) &&
!IsGlobalAliasQualifiedName(name);
}
private static bool IsQualifiedNameInUsingDirective(SemanticModel model, NameSyntax name)
{
while (name.IsLeftSideOfQualifiedName())
{
name = (NameSyntax)name.Parent;
}
if (name.IsParentKind(SyntaxKind.UsingDirective, out UsingDirectiveSyntax usingDirective) &&
usingDirective.Alias == null)
{
// We're a qualified name in a using. We don't want to reduce this name as people like
// fully qualified names in usings so they can properly tell what the name is resolving
// to.
// However, if this name is actually referencing the special Script class, then we do
// want to allow that to be reduced.
return !IsInScriptClass(model, name);
}
return false;
}
private static bool IsGlobalAliasQualifiedName(NameSyntax name)
{
// Checks whether the `global::` alias is applied to the name
return name is AliasQualifiedNameSyntax aliasName &&
aliasName.Alias.Identifier.IsKind(SyntaxKind.GlobalKeyword);
}
private static bool IsInScriptClass(SemanticModel model, NameSyntax name)
{
var symbol = model.GetSymbolInfo(name).Symbol as INamedTypeSymbol;
while (symbol != null)
{
if (symbol.IsScriptClass)
{
return true;
}
symbol = symbol.ContainingType;
}
return false;
}
private static bool PreferPredefinedTypeKeywordInDeclarations(NameSyntax name, OptionSet optionSet, SemanticModel semanticModel)
{
return !name.IsDirectChildOfMemberAccessExpression() &&
!name.InsideCrefReference() &&
!InsideNameOfExpression(name, semanticModel) &&
SimplificationHelpers.PreferPredefinedTypeKeywordInDeclarations(optionSet, semanticModel.Language);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/VisualStudio/Core/Def/ExternalAccess/LegacyCodeAnalysis/LegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Composition;
using Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis.Api;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
namespace Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis
{
[Export(typeof(ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor))]
[Shared]
internal sealed class LegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor
: ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor
{
private readonly IVisualStudioDiagnosticListSuppressionStateService _implementation;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor(IVisualStudioDiagnosticListSuppressionStateService implementation)
=> _implementation = implementation;
public bool CanSuppressSelectedEntries => _implementation.CanSuppressSelectedEntries;
public bool CanSuppressSelectedEntriesInSource => _implementation.CanSuppressSelectedEntriesInSource;
public bool CanSuppressSelectedEntriesInSuppressionFiles => _implementation.CanSuppressSelectedEntriesInSuppressionFiles;
public bool CanRemoveSuppressionsSelectedEntries => _implementation.CanRemoveSuppressionsSelectedEntries;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.Composition;
using Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis.Api;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource;
namespace Microsoft.CodeAnalysis.ExternalAccess.LegacyCodeAnalysis
{
[Export(typeof(ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor))]
[Shared]
internal sealed class LegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor
: ILegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor
{
private readonly IVisualStudioDiagnosticListSuppressionStateService _implementation;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public LegacyCodeAnalysisVisualStudioDiagnosticListSuppressionStateServiceAccessor(IVisualStudioDiagnosticListSuppressionStateService implementation)
=> _implementation = implementation;
public bool CanSuppressSelectedEntries => _implementation.CanSuppressSelectedEntries;
public bool CanSuppressSelectedEntriesInSource => _implementation.CanSuppressSelectedEntriesInSource;
public bool CanSuppressSelectedEntriesInSuppressionFiles => _implementation.CanSuppressSelectedEntriesInSuppressionFiles;
public bool CanRemoveSuppressionsSelectedEntries => _implementation.CanRemoveSuppressionsSelectedEntries;
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/NamingStyles/EditorConfig/EditorConfigNamingStyleParser_SymbolSpec.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal static partial class EditorConfigNamingStyleParser
{
private static bool TryGetSymbolSpec(
string namingRuleTitle,
IReadOnlyDictionary<string, string> conventionsDictionary,
out SymbolSpecification symbolSpec)
{
symbolSpec = null;
if (!TryGetSymbolSpecNameForNamingRule(namingRuleTitle, conventionsDictionary, out var symbolSpecName))
{
return false;
}
var applicableKinds = GetSymbolsApplicableKinds(symbolSpecName, conventionsDictionary);
var applicableAccessibilities = GetSymbolsApplicableAccessibilities(symbolSpecName, conventionsDictionary);
var requiredModifiers = GetSymbolsRequiredModifiers(symbolSpecName, conventionsDictionary);
symbolSpec = new SymbolSpecification(
null,
symbolSpecName,
symbolKindList: applicableKinds,
accessibilityList: applicableAccessibilities,
modifiers: requiredModifiers);
return true;
}
private static bool TryGetSymbolSpecNameForNamingRule(
string namingRuleName,
IReadOnlyDictionary<string, string> conventionsDictionary,
out string symbolSpecName)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.symbols", out symbolSpecName))
{
return symbolSpecName != null;
}
return false;
}
private static ImmutableArray<SymbolKindOrTypeKind> GetSymbolsApplicableKinds(
string symbolSpecName,
IReadOnlyDictionary<string, string> conventionsDictionary)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_symbols.{symbolSpecName}.applicable_kinds", out var result))
{
return ParseSymbolKindList(result ?? string.Empty);
}
return _all;
}
private static readonly SymbolKindOrTypeKind _namespace = new(SymbolKind.Namespace);
private static readonly SymbolKindOrTypeKind _class = new(TypeKind.Class);
private static readonly SymbolKindOrTypeKind _struct = new(TypeKind.Struct);
private static readonly SymbolKindOrTypeKind _interface = new(TypeKind.Interface);
private static readonly SymbolKindOrTypeKind _enum = new(TypeKind.Enum);
private static readonly SymbolKindOrTypeKind _property = new(SymbolKind.Property);
private static readonly SymbolKindOrTypeKind _method = new(MethodKind.Ordinary);
private static readonly SymbolKindOrTypeKind _localFunction = new(MethodKind.LocalFunction);
private static readonly SymbolKindOrTypeKind _field = new(SymbolKind.Field);
private static readonly SymbolKindOrTypeKind _event = new(SymbolKind.Event);
private static readonly SymbolKindOrTypeKind _delegate = new(TypeKind.Delegate);
private static readonly SymbolKindOrTypeKind _parameter = new(SymbolKind.Parameter);
private static readonly SymbolKindOrTypeKind _typeParameter = new(SymbolKind.TypeParameter);
private static readonly SymbolKindOrTypeKind _local = new(SymbolKind.Local);
private static readonly ImmutableArray<SymbolKindOrTypeKind> _all =
ImmutableArray.Create(
_namespace,
_class,
_struct,
_interface,
_enum,
_property,
_method,
_localFunction,
_field,
_event,
_delegate,
_parameter,
_typeParameter,
_local);
private static ImmutableArray<SymbolKindOrTypeKind> ParseSymbolKindList(string symbolSpecApplicableKinds)
{
if (symbolSpecApplicableKinds == null)
{
return ImmutableArray<SymbolKindOrTypeKind>.Empty;
}
if (symbolSpecApplicableKinds.Trim() == "*")
{
return _all;
}
var builder = ArrayBuilder<SymbolKindOrTypeKind>.GetInstance();
foreach (var symbolSpecApplicableKind in symbolSpecApplicableKinds.Split(',').Select(x => x.Trim()))
{
switch (symbolSpecApplicableKind)
{
case "class":
builder.Add(_class);
break;
case "struct":
builder.Add(_struct);
break;
case "interface":
builder.Add(_interface);
break;
case "enum":
builder.Add(_enum);
break;
case "property":
builder.Add(_property);
break;
case "method":
builder.Add(_method);
break;
case "local_function":
builder.Add(_localFunction);
break;
case "field":
builder.Add(_field);
break;
case "event":
builder.Add(_event);
break;
case "delegate":
builder.Add(_delegate);
break;
case "parameter":
builder.Add(_parameter);
break;
case "type_parameter":
builder.Add(_typeParameter);
break;
case "namespace":
builder.Add(_namespace);
break;
case "local":
builder.Add(_local);
break;
default:
break;
}
}
return builder.ToImmutableAndFree();
}
private static ImmutableArray<Accessibility> GetSymbolsApplicableAccessibilities(
string symbolSpecName,
IReadOnlyDictionary<string, string> conventionsDictionary)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_symbols.{symbolSpecName}.applicable_accessibilities", out var result))
{
return ParseAccessibilityKindList(result ?? string.Empty);
}
return _allAccessibility;
}
private static readonly ImmutableArray<Accessibility> _allAccessibility = ImmutableArray.Create(Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal);
private static ImmutableArray<Accessibility> ParseAccessibilityKindList(string symbolSpecApplicableAccessibilities)
{
if (symbolSpecApplicableAccessibilities == null)
{
return ImmutableArray<Accessibility>.Empty;
}
if (symbolSpecApplicableAccessibilities.Trim() == "*")
{
return _allAccessibility;
}
var builder = ArrayBuilder<Accessibility>.GetInstance();
foreach (var symbolSpecApplicableAccessibility in symbolSpecApplicableAccessibilities.Split(',').Select(x => x.Trim()))
{
switch (symbolSpecApplicableAccessibility)
{
case "public":
builder.Add(Accessibility.Public);
break;
case "internal":
case "friend":
builder.Add(Accessibility.Internal);
break;
case "private":
builder.Add(Accessibility.Private);
break;
case "protected":
builder.Add(Accessibility.Protected);
break;
case "protected_internal":
case "protected_friend":
builder.Add(Accessibility.ProtectedOrInternal);
break;
case "private_protected":
builder.Add(Accessibility.ProtectedAndInternal);
break;
case "local":
builder.Add(Accessibility.NotApplicable);
break;
default:
break;
}
}
return builder.ToImmutableAndFree();
}
private static ImmutableArray<ModifierKind> GetSymbolsRequiredModifiers(
string symbolSpecName,
IReadOnlyDictionary<string, string> conventionsDictionary)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_symbols.{symbolSpecName}.required_modifiers", out var result))
{
return ParseModifiers(result ?? string.Empty);
}
return ImmutableArray<ModifierKind>.Empty;
}
private static readonly ModifierKind _abstractModifierKind = new(ModifierKindEnum.IsAbstract);
private static readonly ModifierKind _asyncModifierKind = new(ModifierKindEnum.IsAsync);
private static readonly ModifierKind _constModifierKind = new(ModifierKindEnum.IsConst);
private static readonly ModifierKind _readonlyModifierKind = new(ModifierKindEnum.IsReadOnly);
private static readonly ModifierKind _staticModifierKind = new(ModifierKindEnum.IsStatic);
private static readonly ImmutableArray<ModifierKind> _allModifierKind = ImmutableArray.Create(_abstractModifierKind, _asyncModifierKind, _constModifierKind, _readonlyModifierKind, _staticModifierKind);
private static ImmutableArray<ModifierKind> ParseModifiers(string symbolSpecRequiredModifiers)
{
if (symbolSpecRequiredModifiers == null)
{
return ImmutableArray<ModifierKind>.Empty;
}
if (symbolSpecRequiredModifiers.Trim() == "*")
{
return _allModifierKind;
}
var builder = ArrayBuilder<ModifierKind>.GetInstance();
foreach (var symbolSpecRequiredModifier in symbolSpecRequiredModifiers.Split(',').Select(x => x.Trim()))
{
switch (symbolSpecRequiredModifier)
{
case "abstract":
case "must_inherit":
builder.Add(_abstractModifierKind);
break;
case "async":
builder.Add(_asyncModifierKind);
break;
case "const":
builder.Add(_constModifierKind);
break;
case "readonly":
builder.Add(_readonlyModifierKind);
break;
case "static":
case "shared":
builder.Add(_staticModifierKind);
break;
default:
break;
}
}
return builder.ToImmutableAndFree();
}
public static string ToEditorConfigString(this ImmutableArray<SymbolKindOrTypeKind> symbols)
{
if (symbols.IsDefaultOrEmpty)
{
return "";
}
if (_all.All(symbols.Contains) && symbols.All(_all.Contains))
{
return "*";
}
return string.Join(", ", symbols.Select(symbol => symbol.ToEditorConfigString()));
}
private static string ToEditorConfigString(this SymbolKindOrTypeKind symbol)
{
switch (symbol.MethodKind)
{
case MethodKind.Ordinary:
return "method";
case MethodKind.LocalFunction:
return "local_function";
case null:
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol);
}
switch (symbol.TypeKind)
{
case TypeKind.Class:
return "class";
case TypeKind.Struct:
return "struct";
case TypeKind.Interface:
return "interface";
case TypeKind.Enum:
return "enum";
case TypeKind.Delegate:
return "delegate";
case TypeKind.Module:
return "module";
case TypeKind.Pointer:
return "pointer";
case TypeKind.TypeParameter:
return "type_parameter";
case null:
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol);
}
switch (symbol.SymbolKind)
{
case SymbolKind.Namespace:
return "namespace";
case SymbolKind.Property:
return "property";
case SymbolKind.Field:
return "field";
case SymbolKind.Event:
return "event";
case SymbolKind.Parameter:
return "parameter";
case SymbolKind.TypeParameter:
return "type_parameter";
case SymbolKind.Local:
return "local";
case null:
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol);
}
throw ExceptionUtilities.UnexpectedValue(symbol);
}
public static string ToEditorConfigString(this ImmutableArray<Accessibility> accessibilities, string languageName)
{
if (accessibilities.IsDefaultOrEmpty)
{
return "";
}
if (_allAccessibility.All(accessibilities.Contains) && accessibilities.All(_allAccessibility.Contains))
{
return "*";
}
return string.Join(", ", accessibilities.Select(accessibility => accessibility.ToEditorConfigString(languageName)));
}
private static string ToEditorConfigString(this Accessibility accessibility, string languageName)
{
switch (accessibility)
{
case Accessibility.NotApplicable:
return "local";
case Accessibility.Private:
return "private";
case Accessibility.ProtectedAndInternal:
return "private_protected";
case Accessibility.Protected:
return "protected";
case Accessibility.Internal:
if (languageName == LanguageNames.VisualBasic)
{
return "friend";
}
else
{
return "internal";
}
case Accessibility.ProtectedOrInternal:
if (languageName == LanguageNames.VisualBasic)
{
return "protected_friend";
}
else
{
return "protected_internal";
}
case Accessibility.Public:
return "public";
default:
throw ExceptionUtilities.UnexpectedValue(accessibility);
}
}
public static string ToEditorConfigString(this ImmutableArray<ModifierKind> modifiers, string languageName)
{
if (modifiers.IsDefaultOrEmpty)
{
return "";
}
if (_allModifierKind.All(modifiers.Contains) && modifiers.All(_allModifierKind.Contains))
{
return "*";
}
return string.Join(", ", modifiers.Select(modifier => modifier.ToEditorConfigString(languageName)));
}
private static string ToEditorConfigString(this ModifierKind modifier, string languageName)
{
switch (modifier.ModifierKindWrapper)
{
case ModifierKindEnum.IsAbstract:
if (languageName == LanguageNames.VisualBasic)
{
return "must_inherit";
}
else
{
return "abstract";
}
case ModifierKindEnum.IsStatic:
if (languageName == LanguageNames.VisualBasic)
{
return "shared";
}
else
{
return "static";
}
case ModifierKindEnum.IsAsync:
return "async";
case ModifierKindEnum.IsReadOnly:
return "readonly";
case ModifierKindEnum.IsConst:
return "const";
default:
throw ExceptionUtilities.UnexpectedValue(modifier);
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.PooledObjects;
using Roslyn.Utilities;
using static Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles.SymbolSpecification;
namespace Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles
{
internal static partial class EditorConfigNamingStyleParser
{
private static bool TryGetSymbolSpec(
string namingRuleTitle,
IReadOnlyDictionary<string, string> conventionsDictionary,
out SymbolSpecification symbolSpec)
{
symbolSpec = null;
if (!TryGetSymbolSpecNameForNamingRule(namingRuleTitle, conventionsDictionary, out var symbolSpecName))
{
return false;
}
var applicableKinds = GetSymbolsApplicableKinds(symbolSpecName, conventionsDictionary);
var applicableAccessibilities = GetSymbolsApplicableAccessibilities(symbolSpecName, conventionsDictionary);
var requiredModifiers = GetSymbolsRequiredModifiers(symbolSpecName, conventionsDictionary);
symbolSpec = new SymbolSpecification(
null,
symbolSpecName,
symbolKindList: applicableKinds,
accessibilityList: applicableAccessibilities,
modifiers: requiredModifiers);
return true;
}
private static bool TryGetSymbolSpecNameForNamingRule(
string namingRuleName,
IReadOnlyDictionary<string, string> conventionsDictionary,
out string symbolSpecName)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_rule.{namingRuleName}.symbols", out symbolSpecName))
{
return symbolSpecName != null;
}
return false;
}
private static ImmutableArray<SymbolKindOrTypeKind> GetSymbolsApplicableKinds(
string symbolSpecName,
IReadOnlyDictionary<string, string> conventionsDictionary)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_symbols.{symbolSpecName}.applicable_kinds", out var result))
{
return ParseSymbolKindList(result ?? string.Empty);
}
return _all;
}
private static readonly SymbolKindOrTypeKind _namespace = new(SymbolKind.Namespace);
private static readonly SymbolKindOrTypeKind _class = new(TypeKind.Class);
private static readonly SymbolKindOrTypeKind _struct = new(TypeKind.Struct);
private static readonly SymbolKindOrTypeKind _interface = new(TypeKind.Interface);
private static readonly SymbolKindOrTypeKind _enum = new(TypeKind.Enum);
private static readonly SymbolKindOrTypeKind _property = new(SymbolKind.Property);
private static readonly SymbolKindOrTypeKind _method = new(MethodKind.Ordinary);
private static readonly SymbolKindOrTypeKind _localFunction = new(MethodKind.LocalFunction);
private static readonly SymbolKindOrTypeKind _field = new(SymbolKind.Field);
private static readonly SymbolKindOrTypeKind _event = new(SymbolKind.Event);
private static readonly SymbolKindOrTypeKind _delegate = new(TypeKind.Delegate);
private static readonly SymbolKindOrTypeKind _parameter = new(SymbolKind.Parameter);
private static readonly SymbolKindOrTypeKind _typeParameter = new(SymbolKind.TypeParameter);
private static readonly SymbolKindOrTypeKind _local = new(SymbolKind.Local);
private static readonly ImmutableArray<SymbolKindOrTypeKind> _all =
ImmutableArray.Create(
_namespace,
_class,
_struct,
_interface,
_enum,
_property,
_method,
_localFunction,
_field,
_event,
_delegate,
_parameter,
_typeParameter,
_local);
private static ImmutableArray<SymbolKindOrTypeKind> ParseSymbolKindList(string symbolSpecApplicableKinds)
{
if (symbolSpecApplicableKinds == null)
{
return ImmutableArray<SymbolKindOrTypeKind>.Empty;
}
if (symbolSpecApplicableKinds.Trim() == "*")
{
return _all;
}
var builder = ArrayBuilder<SymbolKindOrTypeKind>.GetInstance();
foreach (var symbolSpecApplicableKind in symbolSpecApplicableKinds.Split(',').Select(x => x.Trim()))
{
switch (symbolSpecApplicableKind)
{
case "class":
builder.Add(_class);
break;
case "struct":
builder.Add(_struct);
break;
case "interface":
builder.Add(_interface);
break;
case "enum":
builder.Add(_enum);
break;
case "property":
builder.Add(_property);
break;
case "method":
builder.Add(_method);
break;
case "local_function":
builder.Add(_localFunction);
break;
case "field":
builder.Add(_field);
break;
case "event":
builder.Add(_event);
break;
case "delegate":
builder.Add(_delegate);
break;
case "parameter":
builder.Add(_parameter);
break;
case "type_parameter":
builder.Add(_typeParameter);
break;
case "namespace":
builder.Add(_namespace);
break;
case "local":
builder.Add(_local);
break;
default:
break;
}
}
return builder.ToImmutableAndFree();
}
private static ImmutableArray<Accessibility> GetSymbolsApplicableAccessibilities(
string symbolSpecName,
IReadOnlyDictionary<string, string> conventionsDictionary)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_symbols.{symbolSpecName}.applicable_accessibilities", out var result))
{
return ParseAccessibilityKindList(result ?? string.Empty);
}
return _allAccessibility;
}
private static readonly ImmutableArray<Accessibility> _allAccessibility = ImmutableArray.Create(Accessibility.NotApplicable, Accessibility.Public, Accessibility.Internal, Accessibility.Private, Accessibility.Protected, Accessibility.ProtectedAndInternal, Accessibility.ProtectedOrInternal);
private static ImmutableArray<Accessibility> ParseAccessibilityKindList(string symbolSpecApplicableAccessibilities)
{
if (symbolSpecApplicableAccessibilities == null)
{
return ImmutableArray<Accessibility>.Empty;
}
if (symbolSpecApplicableAccessibilities.Trim() == "*")
{
return _allAccessibility;
}
var builder = ArrayBuilder<Accessibility>.GetInstance();
foreach (var symbolSpecApplicableAccessibility in symbolSpecApplicableAccessibilities.Split(',').Select(x => x.Trim()))
{
switch (symbolSpecApplicableAccessibility)
{
case "public":
builder.Add(Accessibility.Public);
break;
case "internal":
case "friend":
builder.Add(Accessibility.Internal);
break;
case "private":
builder.Add(Accessibility.Private);
break;
case "protected":
builder.Add(Accessibility.Protected);
break;
case "protected_internal":
case "protected_friend":
builder.Add(Accessibility.ProtectedOrInternal);
break;
case "private_protected":
builder.Add(Accessibility.ProtectedAndInternal);
break;
case "local":
builder.Add(Accessibility.NotApplicable);
break;
default:
break;
}
}
return builder.ToImmutableAndFree();
}
private static ImmutableArray<ModifierKind> GetSymbolsRequiredModifiers(
string symbolSpecName,
IReadOnlyDictionary<string, string> conventionsDictionary)
{
if (conventionsDictionary.TryGetValue($"dotnet_naming_symbols.{symbolSpecName}.required_modifiers", out var result))
{
return ParseModifiers(result ?? string.Empty);
}
return ImmutableArray<ModifierKind>.Empty;
}
private static readonly ModifierKind _abstractModifierKind = new(ModifierKindEnum.IsAbstract);
private static readonly ModifierKind _asyncModifierKind = new(ModifierKindEnum.IsAsync);
private static readonly ModifierKind _constModifierKind = new(ModifierKindEnum.IsConst);
private static readonly ModifierKind _readonlyModifierKind = new(ModifierKindEnum.IsReadOnly);
private static readonly ModifierKind _staticModifierKind = new(ModifierKindEnum.IsStatic);
private static readonly ImmutableArray<ModifierKind> _allModifierKind = ImmutableArray.Create(_abstractModifierKind, _asyncModifierKind, _constModifierKind, _readonlyModifierKind, _staticModifierKind);
private static ImmutableArray<ModifierKind> ParseModifiers(string symbolSpecRequiredModifiers)
{
if (symbolSpecRequiredModifiers == null)
{
return ImmutableArray<ModifierKind>.Empty;
}
if (symbolSpecRequiredModifiers.Trim() == "*")
{
return _allModifierKind;
}
var builder = ArrayBuilder<ModifierKind>.GetInstance();
foreach (var symbolSpecRequiredModifier in symbolSpecRequiredModifiers.Split(',').Select(x => x.Trim()))
{
switch (symbolSpecRequiredModifier)
{
case "abstract":
case "must_inherit":
builder.Add(_abstractModifierKind);
break;
case "async":
builder.Add(_asyncModifierKind);
break;
case "const":
builder.Add(_constModifierKind);
break;
case "readonly":
builder.Add(_readonlyModifierKind);
break;
case "static":
case "shared":
builder.Add(_staticModifierKind);
break;
default:
break;
}
}
return builder.ToImmutableAndFree();
}
public static string ToEditorConfigString(this ImmutableArray<SymbolKindOrTypeKind> symbols)
{
if (symbols.IsDefaultOrEmpty)
{
return "";
}
if (_all.All(symbols.Contains) && symbols.All(_all.Contains))
{
return "*";
}
return string.Join(", ", symbols.Select(symbol => symbol.ToEditorConfigString()));
}
private static string ToEditorConfigString(this SymbolKindOrTypeKind symbol)
{
switch (symbol.MethodKind)
{
case MethodKind.Ordinary:
return "method";
case MethodKind.LocalFunction:
return "local_function";
case null:
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol);
}
switch (symbol.TypeKind)
{
case TypeKind.Class:
return "class";
case TypeKind.Struct:
return "struct";
case TypeKind.Interface:
return "interface";
case TypeKind.Enum:
return "enum";
case TypeKind.Delegate:
return "delegate";
case TypeKind.Module:
return "module";
case TypeKind.Pointer:
return "pointer";
case TypeKind.TypeParameter:
return "type_parameter";
case null:
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol);
}
switch (symbol.SymbolKind)
{
case SymbolKind.Namespace:
return "namespace";
case SymbolKind.Property:
return "property";
case SymbolKind.Field:
return "field";
case SymbolKind.Event:
return "event";
case SymbolKind.Parameter:
return "parameter";
case SymbolKind.TypeParameter:
return "type_parameter";
case SymbolKind.Local:
return "local";
case null:
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol);
}
throw ExceptionUtilities.UnexpectedValue(symbol);
}
public static string ToEditorConfigString(this ImmutableArray<Accessibility> accessibilities, string languageName)
{
if (accessibilities.IsDefaultOrEmpty)
{
return "";
}
if (_allAccessibility.All(accessibilities.Contains) && accessibilities.All(_allAccessibility.Contains))
{
return "*";
}
return string.Join(", ", accessibilities.Select(accessibility => accessibility.ToEditorConfigString(languageName)));
}
private static string ToEditorConfigString(this Accessibility accessibility, string languageName)
{
switch (accessibility)
{
case Accessibility.NotApplicable:
return "local";
case Accessibility.Private:
return "private";
case Accessibility.ProtectedAndInternal:
return "private_protected";
case Accessibility.Protected:
return "protected";
case Accessibility.Internal:
if (languageName == LanguageNames.VisualBasic)
{
return "friend";
}
else
{
return "internal";
}
case Accessibility.ProtectedOrInternal:
if (languageName == LanguageNames.VisualBasic)
{
return "protected_friend";
}
else
{
return "protected_internal";
}
case Accessibility.Public:
return "public";
default:
throw ExceptionUtilities.UnexpectedValue(accessibility);
}
}
public static string ToEditorConfigString(this ImmutableArray<ModifierKind> modifiers, string languageName)
{
if (modifiers.IsDefaultOrEmpty)
{
return "";
}
if (_allModifierKind.All(modifiers.Contains) && modifiers.All(_allModifierKind.Contains))
{
return "*";
}
return string.Join(", ", modifiers.Select(modifier => modifier.ToEditorConfigString(languageName)));
}
private static string ToEditorConfigString(this ModifierKind modifier, string languageName)
{
switch (modifier.ModifierKindWrapper)
{
case ModifierKindEnum.IsAbstract:
if (languageName == LanguageNames.VisualBasic)
{
return "must_inherit";
}
else
{
return "abstract";
}
case ModifierKindEnum.IsStatic:
if (languageName == LanguageNames.VisualBasic)
{
return "shared";
}
else
{
return "static";
}
case ModifierKindEnum.IsAsync:
return "async";
case ModifierKindEnum.IsReadOnly:
return "readonly";
case ModifierKindEnum.IsConst:
return "const";
default:
throw ExceptionUtilities.UnexpectedValue(modifier);
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Analyzers/Core/CodeFixes/RemoveRedundantEquality/RemoveRedundantEqualityCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.RemoveRedundantEquality
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared]
internal sealed class RemoveRedundantEqualityCodeFixProvider
: SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RemoveRedundantEqualityCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId);
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(new MyCodeAction(
AnalyzersResources.Remove_redundant_equality,
c => FixAsync(context.Document, diagnostic, c)),
diagnostic);
}
return Task.CompletedTask;
}
protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
editor.ReplaceNode(node, (n, _) =>
{
if (!syntaxFacts.IsBinaryExpression(n))
{
// This should happen only in error cases.
return n;
}
syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right);
if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right)
{
return WithElasticTrailingTrivia(left);
}
else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left)
{
return WithElasticTrailingTrivia(right);
}
return n;
});
}
return;
static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node)
{
return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic));
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.RemoveRedundantEquality
{
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeFixProviderNames.RemoveRedundantEquality), Shared]
internal sealed class RemoveRedundantEqualityCodeFixProvider
: SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public RemoveRedundantEqualityCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityDiagnosticId);
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(new MyCodeAction(
AnalyzersResources.Remove_redundant_equality,
c => FixAsync(context.Document, diagnostic, c)),
diagnostic);
}
return Task.CompletedTask;
}
protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>();
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.AdditionalLocations[0].SourceSpan, getInnermostNodeForTie: true);
editor.ReplaceNode(node, (n, _) =>
{
if (!syntaxFacts.IsBinaryExpression(n))
{
// This should happen only in error cases.
return n;
}
syntaxFacts.GetPartsOfBinaryExpression(n, out var left, out var right);
if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Right)
{
return WithElasticTrailingTrivia(left);
}
else if (diagnostic.Properties[RedundantEqualityConstants.RedundantSide] == RedundantEqualityConstants.Left)
{
return WithElasticTrailingTrivia(right);
}
return n;
});
}
return;
static SyntaxNode WithElasticTrailingTrivia(SyntaxNode node)
{
return node.WithTrailingTrivia(node.GetTrailingTrivia().Select(SyntaxTriviaExtensions.AsElastic));
}
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Analyzers/CSharp/CodeFixes/UseConditionalExpression/CSharpUseConditionalExpressionHelpers.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression
{
internal static class CSharpUseConditionalExpressionHelpers
{
public static ExpressionSyntax ConvertToExpression(IThrowOperation throwOperation)
{
var throwStatement = (ThrowStatementSyntax)throwOperation.Syntax;
RoslynDebug.Assert(throwStatement.Expression != null);
return SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Operations;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseConditionalExpression
{
internal static class CSharpUseConditionalExpressionHelpers
{
public static ExpressionSyntax ConvertToExpression(IThrowOperation throwOperation)
{
var throwStatement = (ThrowStatementSyntax)throwOperation.Syntax;
RoslynDebug.Assert(throwStatement.Expression != null);
return SyntaxFactory.ThrowExpression(throwStatement.ThrowKeyword, throwStatement.Expression);
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/CSharp/Portable/Symbols/UpdatedContainingSymbolLocal.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class UpdatedContainingSymbolAndNullableAnnotationLocal : LocalSymbol
{
/// <summary>
/// Creates a new <see cref="UpdatedContainingSymbolAndNullableAnnotationLocal"/> for testing purposes,
/// which does not verify that the containing symbol matches the original containing symbol.
/// </summary>
internal static UpdatedContainingSymbolAndNullableAnnotationLocal CreateForTest(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType)
{
return new UpdatedContainingSymbolAndNullableAnnotationLocal(underlyingLocal, updatedContainingSymbol, updatedType, assertContaining: false);
}
private UpdatedContainingSymbolAndNullableAnnotationLocal(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType, bool assertContaining)
{
RoslynDebug.Assert(underlyingLocal is object);
RoslynDebug.Assert(updatedContainingSymbol is object);
Debug.Assert(!assertContaining || updatedContainingSymbol.Equals(underlyingLocal.ContainingSymbol, TypeCompareKind.AllNullableIgnoreOptions));
ContainingSymbol = updatedContainingSymbol;
TypeWithAnnotations = updatedType;
_underlyingLocal = underlyingLocal;
}
internal UpdatedContainingSymbolAndNullableAnnotationLocal(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType)
: this(underlyingLocal, updatedContainingSymbol, updatedType, assertContaining: true)
{
}
private readonly SourceLocalSymbol _underlyingLocal;
public override Symbol ContainingSymbol { get; }
public override TypeWithAnnotations TypeWithAnnotations { get; }
public override bool Equals(Symbol other, TypeCompareKind compareKind)
{
if (other == (object)this)
{
return true;
}
if (!(other is LocalSymbol otherLocal))
{
return false;
}
SourceLocalSymbol? otherSource = otherLocal switch
{
UpdatedContainingSymbolAndNullableAnnotationLocal updated => updated._underlyingLocal,
SourceLocalSymbol source => source,
_ => null
};
if (otherSource is null || !_underlyingLocal.Equals(otherSource, compareKind))
{
return false;
}
var ignoreNullable = (compareKind & TypeCompareKind.AllNullableIgnoreOptions) != 0;
return ignoreNullable ||
(TypeWithAnnotations.Equals(otherLocal.TypeWithAnnotations, compareKind) &&
ContainingSymbol.Equals(otherLocal.ContainingSymbol, compareKind));
}
// The default equality for symbols does not include nullability, so we directly
// delegate to the underlying local for its hashcode, as neither TypeWithAnnotations
// nor ContainingSymbol will differ from UnderlyingLocal by more than nullability.
public override int GetHashCode() => _underlyingLocal.GetHashCode();
#region Forwards
public override RefKind RefKind => _underlyingLocal.RefKind;
public override ImmutableArray<Location> Locations => _underlyingLocal.Locations;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => _underlyingLocal.DeclaringSyntaxReferences;
public override string Name => _underlyingLocal.Name;
public override bool IsImplicitlyDeclared => _underlyingLocal.IsImplicitlyDeclared;
internal override LocalDeclarationKind DeclarationKind => _underlyingLocal.DeclarationKind;
internal override SynthesizedLocalKind SynthesizedKind => _underlyingLocal.SynthesizedKind;
internal override SyntaxNode ScopeDesignatorOpt => _underlyingLocal.ScopeDesignatorOpt;
internal override bool IsImportedFromMetadata => _underlyingLocal.IsImportedFromMetadata;
internal override SyntaxToken IdentifierToken => _underlyingLocal.IdentifierToken;
internal override bool IsPinned => _underlyingLocal.IsPinned;
internal override bool IsCompilerGenerated => _underlyingLocal.IsCompilerGenerated;
internal override uint RefEscapeScope => _underlyingLocal.RefEscapeScope;
internal override uint ValEscapeScope => _underlyingLocal.ValEscapeScope;
internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag? diagnostics = null) =>
_underlyingLocal.GetConstantValue(node, inProgress, diagnostics);
internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue) =>
_underlyingLocal.GetConstantValueDiagnostics(boundInitValue);
internal override SyntaxNode GetDeclaratorSyntax() =>
_underlyingLocal.GetDeclaratorSyntax();
internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) =>
throw ExceptionUtilities.Unreachable;
#endregion
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Immutable;
using System.Diagnostics;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Symbols
{
internal sealed class UpdatedContainingSymbolAndNullableAnnotationLocal : LocalSymbol
{
/// <summary>
/// Creates a new <see cref="UpdatedContainingSymbolAndNullableAnnotationLocal"/> for testing purposes,
/// which does not verify that the containing symbol matches the original containing symbol.
/// </summary>
internal static UpdatedContainingSymbolAndNullableAnnotationLocal CreateForTest(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType)
{
return new UpdatedContainingSymbolAndNullableAnnotationLocal(underlyingLocal, updatedContainingSymbol, updatedType, assertContaining: false);
}
private UpdatedContainingSymbolAndNullableAnnotationLocal(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType, bool assertContaining)
{
RoslynDebug.Assert(underlyingLocal is object);
RoslynDebug.Assert(updatedContainingSymbol is object);
Debug.Assert(!assertContaining || updatedContainingSymbol.Equals(underlyingLocal.ContainingSymbol, TypeCompareKind.AllNullableIgnoreOptions));
ContainingSymbol = updatedContainingSymbol;
TypeWithAnnotations = updatedType;
_underlyingLocal = underlyingLocal;
}
internal UpdatedContainingSymbolAndNullableAnnotationLocal(SourceLocalSymbol underlyingLocal, Symbol updatedContainingSymbol, TypeWithAnnotations updatedType)
: this(underlyingLocal, updatedContainingSymbol, updatedType, assertContaining: true)
{
}
private readonly SourceLocalSymbol _underlyingLocal;
public override Symbol ContainingSymbol { get; }
public override TypeWithAnnotations TypeWithAnnotations { get; }
public override bool Equals(Symbol other, TypeCompareKind compareKind)
{
if (other == (object)this)
{
return true;
}
if (!(other is LocalSymbol otherLocal))
{
return false;
}
SourceLocalSymbol? otherSource = otherLocal switch
{
UpdatedContainingSymbolAndNullableAnnotationLocal updated => updated._underlyingLocal,
SourceLocalSymbol source => source,
_ => null
};
if (otherSource is null || !_underlyingLocal.Equals(otherSource, compareKind))
{
return false;
}
var ignoreNullable = (compareKind & TypeCompareKind.AllNullableIgnoreOptions) != 0;
return ignoreNullable ||
(TypeWithAnnotations.Equals(otherLocal.TypeWithAnnotations, compareKind) &&
ContainingSymbol.Equals(otherLocal.ContainingSymbol, compareKind));
}
// The default equality for symbols does not include nullability, so we directly
// delegate to the underlying local for its hashcode, as neither TypeWithAnnotations
// nor ContainingSymbol will differ from UnderlyingLocal by more than nullability.
public override int GetHashCode() => _underlyingLocal.GetHashCode();
#region Forwards
public override RefKind RefKind => _underlyingLocal.RefKind;
public override ImmutableArray<Location> Locations => _underlyingLocal.Locations;
public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences => _underlyingLocal.DeclaringSyntaxReferences;
public override string Name => _underlyingLocal.Name;
public override bool IsImplicitlyDeclared => _underlyingLocal.IsImplicitlyDeclared;
internal override LocalDeclarationKind DeclarationKind => _underlyingLocal.DeclarationKind;
internal override SynthesizedLocalKind SynthesizedKind => _underlyingLocal.SynthesizedKind;
internal override SyntaxNode ScopeDesignatorOpt => _underlyingLocal.ScopeDesignatorOpt;
internal override bool IsImportedFromMetadata => _underlyingLocal.IsImportedFromMetadata;
internal override SyntaxToken IdentifierToken => _underlyingLocal.IdentifierToken;
internal override bool IsPinned => _underlyingLocal.IsPinned;
internal override bool IsCompilerGenerated => _underlyingLocal.IsCompilerGenerated;
internal override uint RefEscapeScope => _underlyingLocal.RefEscapeScope;
internal override uint ValEscapeScope => _underlyingLocal.ValEscapeScope;
internal override ConstantValue GetConstantValue(SyntaxNode node, LocalSymbol inProgress, BindingDiagnosticBag? diagnostics = null) =>
_underlyingLocal.GetConstantValue(node, inProgress, diagnostics);
internal override ImmutableBindingDiagnostic<AssemblySymbol> GetConstantValueDiagnostics(BoundExpression boundInitValue) =>
_underlyingLocal.GetConstantValueDiagnostics(boundInitValue);
internal override SyntaxNode GetDeclaratorSyntax() =>
_underlyingLocal.GetDeclaratorSyntax();
internal override LocalSymbol WithSynthesizedLocalKindAndSyntax(SynthesizedLocalKind kind, SyntaxNode syntax) =>
throw ExceptionUtilities.Unreachable;
#endregion
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/CSharp/Portable/CodeFixes/ConvertToAsync/CSharpConvertToAsyncMethodCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Async;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ConvertToAsync
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertToAsync), Shared]
internal class CSharpConvertToAsyncMethodCodeFixProvider : AbstractConvertToAsyncCodeFixProvider
{
/// <summary>
/// Cannot await void.
/// </summary>
private const string CS4008 = nameof(CS4008);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpConvertToAsyncMethodCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS4008);
protected override async Task<string> GetDescriptionAsync(
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var methodNode = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
// We only call GetDescription when we already know that we succeeded (so it's safe to
// assume we have a methodNode here).
return string.Format(CSharpFeaturesResources.Make_0_return_Task_instead_of_void, methodNode!.WithBody(null));
}
protected override async Task<Tuple<SyntaxTree, SyntaxNode>?> GetRootInOtherSyntaxTreeAsync(
SyntaxNode node,
SemanticModel semanticModel,
Diagnostic diagnostic,
CancellationToken cancellationToken)
{
var methodDeclaration = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
if (methodDeclaration == null)
{
return null;
}
var oldRoot = await methodDeclaration.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = oldRoot.ReplaceNode(methodDeclaration, ConvertToAsyncFunction(methodDeclaration));
return Tuple.Create(oldRoot.SyntaxTree, newRoot);
}
private static async Task<MethodDeclarationSyntax?> GetMethodDeclarationAsync(
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var invocationExpression = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.InvocationExpression));
if (invocationExpression == null)
{
return null;
}
if (!(semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol))
{
return null;
}
var methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();
if (methodReference == null)
{
return null;
}
if (!((await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) is MethodDeclarationSyntax methodDeclaration))
{
return null;
}
if (!methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
return null;
}
return methodDeclaration;
}
private static MethodDeclarationSyntax ConvertToAsyncFunction(MethodDeclarationSyntax methodDeclaration)
{
return methodDeclaration.WithReturnType(
SyntaxFactory.ParseTypeName("Task")
.WithTriviaFrom(methodDeclaration));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Async;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.CSharp.CodeFixes.ConvertToAsync
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.ConvertToAsync), Shared]
internal class CSharpConvertToAsyncMethodCodeFixProvider : AbstractConvertToAsyncCodeFixProvider
{
/// <summary>
/// Cannot await void.
/// </summary>
private const string CS4008 = nameof(CS4008);
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CSharpConvertToAsyncMethodCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(CS4008);
protected override async Task<string> GetDescriptionAsync(
Diagnostic diagnostic,
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var methodNode = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
// We only call GetDescription when we already know that we succeeded (so it's safe to
// assume we have a methodNode here).
return string.Format(CSharpFeaturesResources.Make_0_return_Task_instead_of_void, methodNode!.WithBody(null));
}
protected override async Task<Tuple<SyntaxTree, SyntaxNode>?> GetRootInOtherSyntaxTreeAsync(
SyntaxNode node,
SemanticModel semanticModel,
Diagnostic diagnostic,
CancellationToken cancellationToken)
{
var methodDeclaration = await GetMethodDeclarationAsync(node, semanticModel, cancellationToken).ConfigureAwait(false);
if (methodDeclaration == null)
{
return null;
}
var oldRoot = await methodDeclaration.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
var newRoot = oldRoot.ReplaceNode(methodDeclaration, ConvertToAsyncFunction(methodDeclaration));
return Tuple.Create(oldRoot.SyntaxTree, newRoot);
}
private static async Task<MethodDeclarationSyntax?> GetMethodDeclarationAsync(
SyntaxNode node,
SemanticModel semanticModel,
CancellationToken cancellationToken)
{
var invocationExpression = node.ChildNodes().FirstOrDefault(n => n.IsKind(SyntaxKind.InvocationExpression));
if (invocationExpression == null)
{
return null;
}
if (!(semanticModel.GetSymbolInfo(invocationExpression, cancellationToken).Symbol is IMethodSymbol methodSymbol))
{
return null;
}
var methodReference = methodSymbol.DeclaringSyntaxReferences.FirstOrDefault();
if (methodReference == null)
{
return null;
}
if (!((await methodReference.GetSyntaxAsync(cancellationToken).ConfigureAwait(false)) is MethodDeclarationSyntax methodDeclaration))
{
return null;
}
if (!methodDeclaration.Modifiers.Any(m => m.IsKind(SyntaxKind.AsyncKeyword)))
{
return null;
}
return methodDeclaration;
}
private static MethodDeclarationSyntax ConvertToAsyncFunction(MethodDeclarationSyntax methodDeclaration)
{
return methodDeclaration.WithReturnType(
SyntaxFactory.ParseTypeName("Task")
.WithTriviaFrom(methodDeclaration));
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/Test2/NavigationBar/VisualBasicNavigationBarTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.VisualBasic
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.VisualBasic
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar
<[UseExportProvider]>
Partial Public Class VisualBasicNavigationBarTests
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")>
Public Async Function TestEventsInInterfaces(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Event Goo As EventHandler
End Interface
</Document>
</Project>
</Workspace>,
host,
Item("I", Glyph.InterfaceInternal, bolded:=True, children:={
Item("Goo", Glyph.EventPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")>
Public Async Function TestEmptyStructure(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Structure S
End Structure
</Document>
</Project>
</Workspace>,
host,
Item("S", Glyph.StructureInternal, bolded:=True, children:={}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")>
Public Async Function TestEmptyInterface(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
End Interface
</Document>
</Project>
</Workspace>,
host,
Item("I", Glyph.InterfaceInternal, bolded:=True, children:={}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestUserDefinedOperators(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Operator -(x As C, y As C) As C
End Operator
Shared Operator +(x As C, y As C) As C
End Operator
Shared Operator +(x As C, y As Integer) As C
End Operator
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True),
Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True),
Item("Operator -", Glyph.Operator, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestSingleConversion(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Narrowing Operator CType(x As C) As Integer
End Operator
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestMultipleConversions(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Narrowing Operator CType(x As C) As Integer
End Operator
Shared Narrowing Operator CType(x As C) As String
End Operator
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True),
Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")>
Public Async Function TestNestedClass(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace N
Class C
Class Nested
End Class
End Class
End Namespace
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True),
Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")>
Public Async Function TestDelegate(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Delegate Sub Goo()
</Document>
</Project>
</Workspace>,
host,
Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")>
Public Async Function TestGenericType(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface C(Of In T)
End Interface
</Document>
</Project>
</Workspace>,
host,
Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")>
Public Async Function TestMethodGroupWithGenericMethod(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S()
End Sub
Sub S(Of T)()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S()", Glyph.MethodPublic, bolded:=True),
Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")>
Public Async Function TestSingleGenericMethod(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S(Of T)()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")>
Public Async Function TestSingleGenericFunction(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Function S(Of T)() As Integer
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestSingleNonGenericMethod(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S(arg As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")>
Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task
Await AssertSelectedItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Class Nested
$$
End Class
End Class
</Document>
</Project>
</Workspace>,
host,
Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")>
Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass(host As TestHost) As Task
Await AssertSelectedItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Z
Class Nested
$$
End Class
End Class
</Document>
</Project>
</Workspace>,
host,
Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")>
Public Async Function TestFinalizer(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Protected Overrides Sub Finalize()
End Class
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")>
Public Async Function TestFieldsAndConstants(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Const Co = 1
Private F As Integer
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Co", Glyph.ConstantPrivate, bolded:=True),
Item("F", Glyph.FieldPrivate, bolded:=True)}))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")>
Public Async Function TestGenerateFinalizer(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "Finalize",
<Result>
Class C
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateConstructor(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "New",
<Result>
Class C
Public Sub New()
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateConstructorInDesignerGeneratedFile(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute>
Class C
Sub InitializeComponent()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "New",
<Result>
<Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute>
Class C
Public Sub New()
' <%= VBEditorResources.This_call_is_required_by_the_designer %>
InitializeComponent()
' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %>
End Sub
Sub InitializeComponent()
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGeneratePartialMethod(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
End Class
</Document>
<Document>
Partial Class C
Private Partial Sub Goo()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "Goo",
<Result>
Partial Class C
Private Sub Goo()
End Sub
End Class
</Result>)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestPartialMethodInDifferentFile(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
End Class
</Document>
<Document>
Partial Class C
Sub Goo()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Goo", Glyph.MethodPublic, grayed:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")>
Public Async Function TestWithEventsField(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private WithEvents goo As System.Console
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={
Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")>
Public Async Function TestWithEventsField_EventsFromInheritedInterfaces(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I1
Event I1Event(sender As Object, e As EventArgs)
End Interface
Interface I2
Event I2Event(sender As Object, e As EventArgs)
End Interface
Interface I3
Inherits I1, I2
Event I3Event(sender As Object, e As EventArgs)
End Interface
Class Test
WithEvents i3 As I3
End Class
</Document>
</Project>
</Workspace>,
host,
Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I1Event", Glyph.EventPublic, bolded:=True)}),
Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I2Event", Glyph.EventPublic, bolded:=True)}),
Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I3Event", Glyph.EventPublic, bolded:=True)}),
Item("Test", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestDoNotIncludeShadowedEvents(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class B
Event E(sender As Object, e As EventArgs)
End Class
Class C
Inherits B
Shadows Event E(sender As Object, e As EventArgs)
End Class
Class Test
WithEvents c As C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("B", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}),
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node
Item("Test", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event E()
End Class
Class D
Inherits C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}),
Item("D", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBFeaturesResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Event E()
End Class
Class D
Inherits C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPrivate, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("D", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Event E0()
Protected Event E1()
Private Event E2()
Class N1
Class N2
Inherits C
End Class
End Class
End Class
Class D2
Inherits C
End Class
Class T
WithEvents c As C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E0", Glyph.EventPublic, bolded:=True),
Item("E1", Glyph.EventProtected, bolded:=True),
Item("E2", Glyph.EventPrivate, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False),
Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("D2", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBFeaturesResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}),
Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBFeaturesResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False),
Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("T", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandler(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private WithEvents goo As System.Console
End Class
</Document>
</Project>
</Workspace>,
host,
"goo", "CancelKeyPress",
<Result>
Class C
Private WithEvents goo As System.Console
Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")>
Public Async Function TestGenerateEventHandlerWithEscapedName(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event [Rem] As System.Action
End Class
</Document>
</Project>
</Workspace>,
host,
String.Format(VBFeaturesResources._0_Events, "C"), "Rem",
<Result>
Class C
Event [Rem] As System.Action
Private Sub C_Rem() Handles Me.[Rem]
End Sub
End Class
</Result>)
End Function
<WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandlerWithRemName(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Event E As Action
WithEvents [Rem] As C
End Class
</Document>
</Project>
</Workspace>,
host,
"Rem", "E",
<Result>
Imports System
Class C
Event E As Action
WithEvents [Rem] As C
Private Sub Rem_E() Handles [Rem].E
End Sub
End Class
</Result>)
End Function
<ConditionalWpfTheory(GetType(IsEnglishLocal)), CombinatorialData>
<WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")>
<WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")>
<Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandlerWithDuplicate(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class ExampleClass
Public Event ExampleEvent()
Public Event ExampleEvent()
End Class
</Document>
</Project>
</Workspace>,
host,
$"(ExampleClass { FeaturesResources.Events })",
Function(items) items.First(Function(i) i.Text = "ExampleEvent"),
<Result>
Public Class ExampleClass
Public Event ExampleEvent()
Public Event ExampleEvent()
Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent
End Sub
End Class
</Result>)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNoListedEventToGenerateWithInvalidTypeName(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event BindingError As System.FogBar
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)},
bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")>
Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges(host As TestHost) As Task
Dim workspaceSupportsChangeDocument = False
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
Private WithEvents M As System.Console
End Class
Partial Class C
Partial Private Sub S()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
workspaceSupportsChangeDocument,
Item("C", Glyph.ClassInternal, bolded:=True),
Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")>
Public Async Function TestEnum(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Enum MyEnum
A
B
C
End Enum
</Document>
</Project>
</Workspace>,
host,
Item("MyEnum", Glyph.EnumInternal, children:={
Item("A", Glyph.EnumMemberPublic),
Item("B", Glyph.EnumMemberPublic),
Item("C", Glyph.EnumMemberPublic)},
bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestEvents(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Base
Public WithEvents o1 As New Class1
Public WithEvents o2 As New Class1
Public Class Class1
' Declare an event.
Public Event Ev_Event()
End Class
$$
Sub EventHandler() Handles o1.Ev_Event
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("Base", Glyph.ClassPublic, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)},
bolded:=True),
Item("o1", Glyph.FieldPublic, children:={
Item("Ev_Event", Glyph.EventPublic, bolded:=True)},
bolded:=False,
hasNavigationSymbolId:=False,
indent:=1),
Item("o2", Glyph.FieldPublic, children:={
Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)},
bolded:=False,
hasNavigationSymbolId:=False,
indent:=1),
Item("Class1 (Base)", Glyph.ClassPublic, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Ev_Event", Glyph.EventPublic, bolded:=True)},
bolded:=True),
Item(String.Format(VBFeaturesResources._0_Events, "Class1"), Glyph.EventPublic, children:={
Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)},
bolded:=False,
indent:=1,
hasNavigationSymbolId:=False))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBetweenFiles(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Source.vb">
Partial Class Program
Sub StartingFile()
End Sub
End Class
</Document>
<Document FilePath="Sink.vb">
Partial Class Program
Sub MethodThatWastesTwoLines()
End Sub
Sub TargetMethod()
$$End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Source.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="TargetMethod")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")>
Public Async Function TestNavigationWithMethodWithLineContinuation(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Iterator Function SomeNumbers() _
As System.Collections.IEnumerable
$$Yield 3
Yield 5
Yield 8
End Function
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="SomeNumbers")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")>
Public Async Function TestNavigationWithMethodWithNoTerminator(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
$$Private Sub S()
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")>
Public Async Function TestNavigationWithMethodWithDocumentationComment(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb"><![CDATA[
Partial Class Program
''' <summary></summary>
$$Private Sub S()
End Class
]]></Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")>
Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(
value As Integer
)
$$Exit Sub
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingComment(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$' Goo
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S",
expectedVirtualSpace:=8)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S",
expectedVirtualSpace:=4)
End Function
<WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function DifferentMembersMetadataName(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Function Get_P(o As Object) As Object
Return od
End Function
ReadOnly Property P As Object
Get
Return Nothing
End Get
End Property
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Get_P", Glyph.MethodPublic, bolded:=True),
Item("P", Glyph.PropertyPublic, bolded:=True)}))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37621, "https://github.com/dotnet/roslyn/issues/37621")>
Public Async Function TestGenerateEventWithAttributedDelegateType(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>LibraryWithInaccessibleAttribute</ProjectReference>
<Document>
Class C
Inherits BaseType
End Class
</Document>
</Project>
<Project Language="Visual Basic" Name="LibraryWithInaccessibleAttribute" CommonReferences="true">
<Document><![CDATA[[
Friend Class AttributeType
Inherits Attribute
End Class
Delegate Sub DelegateType(<AttributeType> parameterWithInaccessibleAttribute As Object)
Public Class BaseType
Public Event E As DelegateType
End Class
]]></Document></Project>
</Workspace>,
host,
String.Format(VBFeaturesResources._0_Events, "C"), "E",
<Result>
Class C
Inherits BaseType
Private Sub C_E(parameterWithInaccessibleAttribute As Object) Handles Me.E
End Sub
End Class
</Result>)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading.Tasks
Imports Microsoft.CodeAnalysis.Editor.VisualBasic
Imports Microsoft.CodeAnalysis.Remote.Testing
Imports Microsoft.CodeAnalysis.VisualBasic
Namespace Microsoft.CodeAnalysis.Editor.UnitTests.NavigationBar
<[UseExportProvider]>
Partial Public Class VisualBasicNavigationBarTests
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545000, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545000")>
Public Async Function TestEventsInInterfaces(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
Event Goo As EventHandler
End Interface
</Document>
</Project>
</Workspace>,
host,
Item("I", Glyph.InterfaceInternal, bolded:=True, children:={
Item("Goo", Glyph.EventPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")>
Public Async Function TestEmptyStructure(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Structure S
End Structure
</Document>
</Project>
</Workspace>,
host,
Item("S", Glyph.StructureInternal, bolded:=True, children:={}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544996, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544996")>
Public Async Function TestEmptyInterface(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I
End Interface
</Document>
</Project>
</Workspace>,
host,
Item("I", Glyph.InterfaceInternal, bolded:=True, children:={}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestUserDefinedOperators(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Operator -(x As C, y As C) As C
End Operator
Shared Operator +(x As C, y As C) As C
End Operator
Shared Operator +(x As C, y As Integer) As C
End Operator
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Operator +(C, C) As C", Glyph.Operator, bolded:=True),
Item("Operator +(C, Integer) As C", Glyph.Operator, bolded:=True),
Item("Operator -", Glyph.Operator, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestSingleConversion(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Narrowing Operator CType(x As C) As Integer
End Operator
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Narrowing Operator CType", Glyph.Operator, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(797455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/797455")>
Public Async Function TestMultipleConversions(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Shared Narrowing Operator CType(x As C) As Integer
End Operator
Shared Narrowing Operator CType(x As C) As String
End Operator
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Narrowing Operator CType(C) As Integer", Glyph.Operator, bolded:=True),
Item("Narrowing Operator CType(C) As String", Glyph.Operator, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544993")>
Public Async Function TestNestedClass(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Namespace N
Class C
Class Nested
End Class
End Class
End Namespace
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True),
Item("Nested (N.C)", Glyph.ClassPublic, bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544997, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544997")>
Public Async Function TestDelegate(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Delegate Sub Goo()
</Document>
</Project>
</Workspace>,
host,
Item("Goo", Glyph.DelegateInternal, children:={}, bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544995, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544995"), WorkItem(545283, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545283")>
Public Async Function TestGenericType(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface C(Of In T)
End Interface
</Document>
</Project>
</Workspace>,
host,
Item("C(Of In T)", Glyph.InterfaceInternal, bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")>
Public Async Function TestMethodGroupWithGenericMethod(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S()
End Sub
Sub S(Of T)()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S()", Glyph.MethodPublic, bolded:=True),
Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545113, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545113")>
Public Async Function TestSingleGenericMethod(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S(Of T)()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S(Of T)()", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545285, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545285")>
Public Async Function TestSingleGenericFunction(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Function S(Of T)() As Integer
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S(Of T)() As Integer", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestSingleNonGenericMethod(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Sub S(arg As Integer)
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("S", Glyph.MethodPublic, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544994, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544994")>
Public Async Function TestSelectedItemForNestedClass(host As TestHost) As Task
Await AssertSelectedItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Class Nested
$$
End Class
End Class
</Document>
</Project>
</Workspace>,
host,
Item("Nested (C)", Glyph.ClassPublic, bolded:=True), False, Nothing, False)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(899330, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/899330")>
Public Async Function TestSelectedItemForNestedClassAlphabeticallyBeforeContainingClass(host As TestHost) As Task
Await AssertSelectedItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class Z
Class Nested
$$
End Class
End Class
</Document>
</Project>
</Workspace>,
host,
Item("Nested (Z)", Glyph.ClassPublic, bolded:=True), False, Nothing, False)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544990, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544990")>
Public Async Function TestFinalizer(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Protected Overrides Sub Finalize()
End Class
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(556, "https://github.com/dotnet/roslyn/issues/556")>
Public Async Function TestFieldsAndConstants(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Const Co = 1
Private F As Integer
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Co", Glyph.ConstantPrivate, bolded:=True),
Item("F", Glyph.FieldPrivate, bolded:=True)}))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544988, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544988")>
Public Async Function TestGenerateFinalizer(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "Finalize",
<Result>
Class C
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateConstructor(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "New",
<Result>
Class C
Public Sub New()
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateConstructorInDesignerGeneratedFile(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
<Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute>
Class C
Sub InitializeComponent()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "New",
<Result>
<Microsoft.VisualBasic.CompilerServices.DesignerGeneratedAttribute>
Class C
Public Sub New()
' <%= VBEditorResources.This_call_is_required_by_the_designer %>
InitializeComponent()
' <%= VBEditorResources.Add_any_initialization_after_the_InitializeComponent_call %>
End Sub
Sub InitializeComponent()
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGeneratePartialMethod(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
End Class
</Document>
<Document>
Partial Class C
Private Partial Sub Goo()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
"C", "Goo",
<Result>
Partial Class C
Private Sub Goo()
End Sub
End Class
</Result>)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestPartialMethodInDifferentFile(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
End Class
</Document>
<Document>
Partial Class C
Sub Goo()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Goo", Glyph.MethodPublic, grayed:=True)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(544991, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544991")>
Public Async Function TestWithEventsField(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private WithEvents goo As System.Console
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("goo", Glyph.FieldPrivate, bolded:=False, hasNavigationSymbolId:=False, indent:=1, children:={
Item("CancelKeyPress", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589")>
Public Async Function TestWithEventsField_EventsFromInheritedInterfaces(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Interface I1
Event I1Event(sender As Object, e As EventArgs)
End Interface
Interface I2
Event I2Event(sender As Object, e As EventArgs)
End Interface
Interface I3
Inherits I1, I2
Event I3Event(sender As Object, e As EventArgs)
End Interface
Class Test
WithEvents i3 As I3
End Class
</Document>
</Project>
</Workspace>,
host,
Item("I1", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I1Event", Glyph.EventPublic, bolded:=True)}),
Item("I2", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I2Event", Glyph.EventPublic, bolded:=True)}),
Item("I3", Glyph.InterfaceInternal, bolded:=True, children:={
Item("I3Event", Glyph.EventPublic, bolded:=True)}),
Item("Test", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("i3", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("I1Event", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("I2Event", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("I3Event", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestDoNotIncludeShadowedEvents(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class B
Event E(sender As Object, e As EventArgs)
End Class
Class C
Inherits B
Shadows Event E(sender As Object, e As EventArgs)
End Class
Class Test
WithEvents c As C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("B", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "B"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}),
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}), ' Only one E under the "(C Events)" node
Item("Test", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)})) ' Only one E for WithEvents handling
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_EnsureInternalEventsInEventListAndInInheritedEventList(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event E()
End Class
Class D
Inherits C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPublic, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}),
Item("D", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBFeaturesResources._0_Events, "D"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_EnsurePrivateEventsInEventListButNotInInheritedEventList(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private Event E()
End Class
Class D
Inherits C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E", Glyph.EventPrivate, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("D", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(1185589, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1185589"), WorkItem(530506, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530506")>
Public Async Function TestEventList_TestAccessibilityThroughNestedAndDerivedTypes(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Public Event E0()
Protected Event E1()
Private Event E2()
Class N1
Class N2
Inherits C
End Class
End Class
End Class
Class D2
Inherits C
End Class
Class T
WithEvents c As C
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("E0", Glyph.EventPublic, bolded:=True),
Item("E1", Glyph.EventProtected, bolded:=True),
Item("E2", Glyph.EventPrivate, bolded:=True)}),
Item(String.Format(VBFeaturesResources._0_Events, "C"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False),
Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("D2", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBFeaturesResources._0_Events, "D2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False)}),
Item("N1 (C)", Glyph.ClassPublic, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("N2 (C.N1)", Glyph.ClassPublic, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item(String.Format(VBFeaturesResources._0_Events, "N2"), Glyph.EventPublic, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False),
Item("E1", Glyph.EventProtected, hasNavigationSymbolId:=False),
Item("E2", Glyph.EventPrivate, hasNavigationSymbolId:=False)}),
Item("T", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)}),
Item("c", Glyph.FieldPrivate, hasNavigationSymbolId:=False, indent:=1, children:={
Item("E0", Glyph.EventPublic, hasNavigationSymbolId:=False)}))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandler(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Private WithEvents goo As System.Console
End Class
</Document>
</Project>
</Workspace>,
host,
"goo", "CancelKeyPress",
<Result>
Class C
Private WithEvents goo As System.Console
Private Sub goo_CancelKeyPress(sender As Object, e As ConsoleCancelEventArgs) Handles goo.CancelKeyPress
End Sub
End Class
</Result>)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(529946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529946")>
Public Async Function TestGenerateEventHandlerWithEscapedName(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event [Rem] As System.Action
End Class
</Document>
</Project>
</Workspace>,
host,
String.Format(VBFeaturesResources._0_Events, "C"), "Rem",
<Result>
Class C
Event [Rem] As System.Action
Private Sub C_Rem() Handles Me.[Rem]
End Sub
End Class
</Result>)
End Function
<WorkItem(546152, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546152")>
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandlerWithRemName(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Imports System
Class C
Event E As Action
WithEvents [Rem] As C
End Class
</Document>
</Project>
</Workspace>,
host,
"Rem", "E",
<Result>
Imports System
Class C
Event E As Action
WithEvents [Rem] As C
Private Sub Rem_E() Handles [Rem].E
End Sub
End Class
</Result>)
End Function
<ConditionalWpfTheory(GetType(IsEnglishLocal)), CombinatorialData>
<WorkItem(25763, "https://github.com/dotnet/roslyn/issues/25763")>
<WorkItem(18792, "https://github.com/dotnet/roslyn/issues/18792")>
<Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestGenerateEventHandlerWithDuplicate(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class ExampleClass
Public Event ExampleEvent()
Public Event ExampleEvent()
End Class
</Document>
</Project>
</Workspace>,
host,
$"(ExampleClass { FeaturesResources.Events })",
Function(items) items.First(Function(i) i.Text = "ExampleEvent"),
<Result>
Public Class ExampleClass
Public Event ExampleEvent()
Public Event ExampleEvent()
Private Sub ExampleClass_ExampleEvent() Handles Me.ExampleEvent
End Sub
End Class
</Result>)
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNoListedEventToGenerateWithInvalidTypeName(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Event BindingError As System.FogBar
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("BindingError", Glyph.EventPublic, hasNavigationSymbolId:=True, bolded:=True)},
bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(530657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530657")>
Public Async Function TestCodeGenerationItemsShouldNotAppearWhenWorkspaceDoesNotSupportDocumentChanges(host As TestHost) As Task
Dim workspaceSupportsChangeDocument = False
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Partial Class C
Private WithEvents M As System.Console
End Class
Partial Class C
Partial Private Sub S()
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
workspaceSupportsChangeDocument,
Item("C", Glyph.ClassInternal, bolded:=True),
Item("M", Glyph.FieldPrivate, indent:=1, hasNavigationSymbolId:=False))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(545220, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545220")>
Public Async Function TestEnum(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Enum MyEnum
A
B
C
End Enum
</Document>
</Project>
</Workspace>,
host,
Item("MyEnum", Glyph.EnumInternal, children:={
Item("A", Glyph.EnumMemberPublic),
Item("B", Glyph.EnumMemberPublic),
Item("C", Glyph.EnumMemberPublic)},
bolded:=True))
End Function
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestEvents(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Public Class Base
Public WithEvents o1 As New Class1
Public WithEvents o2 As New Class1
Public Class Class1
' Declare an event.
Public Event Ev_Event()
End Class
$$
Sub EventHandler() Handles o1.Ev_Event
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
Item("Base", Glyph.ClassPublic, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False)},
bolded:=True),
Item("o1", Glyph.FieldPublic, children:={
Item("Ev_Event", Glyph.EventPublic, bolded:=True)},
bolded:=False,
hasNavigationSymbolId:=False,
indent:=1),
Item("o2", Glyph.FieldPublic, children:={
Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)},
bolded:=False,
hasNavigationSymbolId:=False,
indent:=1),
Item("Class1 (Base)", Glyph.ClassPublic, children:={
Item("New", Glyph.MethodPublic, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, hasNavigationSymbolId:=False),
Item("Ev_Event", Glyph.EventPublic, bolded:=True)},
bolded:=True),
Item(String.Format(VBFeaturesResources._0_Events, "Class1"), Glyph.EventPublic, children:={
Item("Ev_Event", Glyph.EventPublic, hasNavigationSymbolId:=False)},
bolded:=False,
indent:=1,
hasNavigationSymbolId:=False))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function TestNavigationBetweenFiles(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Source.vb">
Partial Class Program
Sub StartingFile()
End Sub
End Class
</Document>
<Document FilePath="Sink.vb">
Partial Class Program
Sub MethodThatWastesTwoLines()
End Sub
Sub TargetMethod()
$$End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Source.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="TargetMethod")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(566752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/566752")>
Public Async Function TestNavigationWithMethodWithLineContinuation(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Iterator Function SomeNumbers() _
As System.Collections.IEnumerable
$$Yield 3
Yield 5
Yield 8
End Function
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="SomeNumbers")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")>
Public Async Function TestNavigationWithMethodWithNoTerminator(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
$$Private Sub S()
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(531586, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531586")>
Public Async Function TestNavigationWithMethodWithDocumentationComment(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb"><![CDATA[
Partial Class Program
''' <summary></summary>
$$Private Sub S()
End Class
]]></Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(567914, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/567914")>
Public Async Function TestNavigationWithMethodWithMultipleLineDeclaration(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(
value As Integer
)
$$Exit Sub
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingComment(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$' Goo
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithSpaces(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S")
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithNoSpaces(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S",
expectedVirtualSpace:=8)
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(605074, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/605074")>
Public Async Function TestNavigationWithMethodContainingBlankLineWithSomeSpaces(host As TestHost) As Task
Await AssertNavigationPointAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document FilePath="Code.vb">
Partial Class Program
Private Sub S(value As Integer)
$$
End Sub
End Class
</Document>
</Project>
</Workspace>,
host,
startingDocumentFilePath:="Code.vb",
leftItemToSelectText:="Program",
rightItemToSelectText:="S",
expectedVirtualSpace:=4)
End Function
<WorkItem(187865, "https://devdiv.visualstudio.com:443/defaultcollection/DevDiv/_workitems/edit/187865")>
<Theory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar)>
Public Async Function DifferentMembersMetadataName(host As TestHost) As Task
Await AssertItemsAreAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<Document>
Class C
Function Get_P(o As Object) As Object
Return od
End Function
ReadOnly Property P As Object
Get
Return Nothing
End Get
End Property
End Class
</Document>
</Project>
</Workspace>,
host,
Item("C", Glyph.ClassInternal, bolded:=True, children:={
Item("New", Glyph.MethodPublic, bolded:=False, hasNavigationSymbolId:=False),
Item("Finalize", Glyph.MethodProtected, bolded:=False, hasNavigationSymbolId:=False),
Item("Get_P", Glyph.MethodPublic, bolded:=True),
Item("P", Glyph.PropertyPublic, bolded:=True)}))
End Function
<WpfTheory, CombinatorialData, Trait(Traits.Feature, Traits.Features.NavigationBar), WorkItem(37621, "https://github.com/dotnet/roslyn/issues/37621")>
Public Async Function TestGenerateEventWithAttributedDelegateType(host As TestHost) As Task
Await AssertGeneratedResultIsAsync(
<Workspace>
<Project Language="Visual Basic" CommonReferences="true">
<ProjectReference>LibraryWithInaccessibleAttribute</ProjectReference>
<Document>
Class C
Inherits BaseType
End Class
</Document>
</Project>
<Project Language="Visual Basic" Name="LibraryWithInaccessibleAttribute" CommonReferences="true">
<Document><![CDATA[[
Friend Class AttributeType
Inherits Attribute
End Class
Delegate Sub DelegateType(<AttributeType> parameterWithInaccessibleAttribute As Object)
Public Class BaseType
Public Event E As DelegateType
End Class
]]></Document></Project>
</Workspace>,
host,
String.Format(VBFeaturesResources._0_Events, "C"), "E",
<Result>
Class C
Inherits BaseType
Private Sub C_E(parameterWithInaccessibleAttribute As Object) Handles Me.E
End Sub
End Class
</Result>)
End Function
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/VisualStudio/VisualBasic/Impl/Options/AdvancedOptionPageStrings.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.ColorSchemes
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Module AdvancedOptionPageStrings
Public ReadOnly Property Option_AutomaticInsertionOfInterfaceAndMustOverrideMembers As String
Get
Return BasicVSResources.Automatic_insertion_of_Interface_and_MustOverride_members
End Get
End Property
Public ReadOnly Property Option_Analysis As String =
ServicesVSResources.Analysis
Public ReadOnly Property Option_Background_analysis_scope As String =
ServicesVSResources.Background_analysis_scope_colon
Public ReadOnly Property Option_Background_Analysis_Scope_Active_File As String =
ServicesVSResources.Current_document
Public ReadOnly Property Option_Background_Analysis_Scope_Open_Files_And_Projects As String =
ServicesVSResources.Open_documents
Public ReadOnly Property Option_Background_Analysis_Scope_Full_Solution As String =
ServicesVSResources.Entire_solution
Public ReadOnly Property Option_run_code_analysis_in_separate_process As String =
ServicesVSResources.Run_code_analysis_in_separate_process_requires_restart
Public ReadOnly Property Option_DisplayLineSeparators As String =
BasicVSResources.Show_procedure_line_separators
Public ReadOnly Property Option_Underline_reassigned_variables As String =
ServicesVSResources.Underline_reassigned_variables
Public ReadOnly Property Option_Display_all_hints_while_pressing_Alt_F1 As String =
ServicesVSResources.Display_all_hints_while_pressing_Alt_F1
Public ReadOnly Property Option_Color_hints As String =
ServicesVSResources.Color_hints
Public ReadOnly Property Option_Inline_Hints As String =
ServicesVSResources.Inline_Hints
Public ReadOnly Property Option_Display_inline_parameter_name_hints As String =
ServicesVSResources.Display_inline_parameter_name_hints
Public ReadOnly Property Option_Show_hints_for_literals As String =
ServicesVSResources.Show_hints_for_literals
Public ReadOnly Property Option_Show_hints_for_New_expressions As String =
BasicVSResources.Show_hints_for_New_expressions
Public ReadOnly Property Option_Show_hints_for_everything_else As String =
ServicesVSResources.Show_hints_for_everything_else
Public ReadOnly Property Option_Show_hints_for_indexers As String =
ServicesVSResources.Show_hints_for_indexers
Public ReadOnly Property Option_Suppress_hints_when_parameter_name_matches_the_method_s_intent As String =
ServicesVSResources.Suppress_hints_when_parameter_name_matches_the_method_s_intent
Public ReadOnly Property Option_Suppress_hints_when_parameter_names_differ_only_by_suffix As String =
ServicesVSResources.Suppress_hints_when_parameter_names_differ_only_by_suffix
Public ReadOnly Property Option_DontPutOutOrRefOnStruct As String =
BasicVSResources.Don_t_put_ByRef_on_custom_structure
Public ReadOnly Property Option_EditorHelp As String =
BasicVSResources.Editor_Help
Public ReadOnly Property Option_EnableEndConstruct As String =
BasicVSResources.A_utomatic_insertion_of_end_constructs
Public ReadOnly Property Option_EnableHighlightKeywords As String =
BasicVSResources.Highlight_related_keywords_under_cursor
Public ReadOnly Property Option_EnableHighlightReferences As String =
BasicVSResources.Highlight_references_to_symbol_under_cursor
Public ReadOnly Property Option_Quick_Actions As String =
ServicesVSResources.Quick_Actions
Public ReadOnly Property Option_Compute_Quick_Actions_asynchronously_experimental As String =
ServicesVSResources.Compute_Quick_Actions_asynchronously_experimental
Public ReadOnly Property Option_EnableLineCommit As String
Get
Return BasicVSResources.Pretty_listing_reformatting_of_code
End Get
End Property
Public ReadOnly Property Option_EnableOutlining As String
Get
Return BasicVSResources.Enter_outlining_mode_when_files_open
End Get
End Property
Public ReadOnly Property Option_ExtractMethod As String
Get
Return BasicVSResources.Extract_Method
End Get
End Property
Public ReadOnly Property Option_Implement_Interface_or_Abstract_Class As String =
ServicesVSResources.Implement_Interface_or_Abstract_Class
Public ReadOnly Property Option_When_inserting_properties_events_and_methods_place_them As String =
ServicesVSResources.When_inserting_properties_events_and_methods_place_them
Public ReadOnly Property Option_with_other_members_of_the_same_kind As String =
ServicesVSResources.with_other_members_of_the_same_kind
Public ReadOnly Property Option_When_generating_properties As String =
ServicesVSResources.When_generating_properties
Public ReadOnly Property Option_prefer_auto_properties As String =
ServicesVSResources.codegen_prefer_auto_properties
Public ReadOnly Property Option_prefer_throwing_properties As String =
ServicesVSResources.prefer_throwing_properties
Public ReadOnly Property Option_at_the_end As String =
ServicesVSResources.at_the_end
Public ReadOnly Property Option_GenerateXmlDocCommentsForTripleApostrophes As String =
BasicVSResources.Generate_XML_documentation_comments_for
Public ReadOnly Property Option_InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments As String =
BasicVSResources.Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments
Public ReadOnly Property Option_ShowRemarksInQuickInfo As String
Get
Return BasicVSResources.Show_remarks_in_Quick_Info
End Get
End Property
Public ReadOnly Property Option_GoToDefinition As String
Get
Return BasicVSResources.Go_to_Definition
End Get
End Property
Public ReadOnly Property Option_Highlighting As String
Get
Return BasicVSResources.Highlighting
End Get
End Property
Public ReadOnly Property Option_NavigateToObjectBrowser As String
Get
Return BasicVSResources.Navigate_to_Object_Browser_for_symbols_defined_in_metadata
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize As String
Get
Return BasicVSResources.Optimize_for_solution_size
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Small As String
Get
Return BasicVSResources.Small
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Regular As String
Get
Return BasicVSResources.Regular
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Large As String
Get
Return BasicVSResources.Large
End Get
End Property
Public ReadOnly Property Option_Outlining As String = ServicesVSResources.Outlining
Public ReadOnly Property Option_Show_outlining_for_declaration_level_constructs As String =
ServicesVSResources.Show_outlining_for_declaration_level_constructs
Public ReadOnly Property Option_Show_outlining_for_code_level_constructs As String =
ServicesVSResources.Show_outlining_for_code_level_constructs
Public ReadOnly Property Option_Show_outlining_for_comments_and_preprocessor_regions As String =
ServicesVSResources.Show_outlining_for_comments_and_preprocessor_regions
Public ReadOnly Property Option_Collapse_regions_when_collapsing_to_definitions As String =
ServicesVSResources.Collapse_regions_when_collapsing_to_definitions
Public ReadOnly Property Option_Block_Structure_Guides As String =
ServicesVSResources.Block_Structure_Guides
Public ReadOnly Property Option_Comments As String =
ServicesVSResources.Comments
Public ReadOnly Property Option_Show_guides_for_declaration_level_constructs As String =
ServicesVSResources.Show_guides_for_declaration_level_constructs
Public ReadOnly Property Option_Show_guides_for_code_level_constructs As String =
ServicesVSResources.Show_guides_for_code_level_constructs
Public ReadOnly Property Option_Fading As String = ServicesVSResources.Fading
Public ReadOnly Property Option_Fade_out_unused_imports As String = BasicVSResources.Fade_out_unused_imports
Public ReadOnly Property Option_Performance As String
Get
Return BasicVSResources.Performance
End Get
End Property
Public ReadOnly Property Option_Report_invalid_placeholders_in_string_dot_format_calls As String
Get
Return BasicVSResources.Report_invalid_placeholders_in_string_dot_format_calls
End Get
End Property
Public ReadOnly Property Option_RenameTrackingPreview As String
Get
Return BasicVSResources.Show_preview_for_rename_tracking
End Get
End Property
Public ReadOnly Property Option_Import_Directives As String =
BasicVSResources.Import_Directives
Public ReadOnly Property Option_PlaceSystemNamespaceFirst As String =
BasicVSResources.Place_System_directives_first_when_sorting_imports
Public ReadOnly Property Option_SeparateImportGroups As String =
BasicVSResources.Separate_import_directive_groups
Public ReadOnly Property Option_Suggest_imports_for_types_in_reference_assemblies As String =
BasicVSResources.Suggest_imports_for_types_in_reference_assemblies
Public ReadOnly Property Option_Suggest_imports_for_types_in_NuGet_packages As String =
BasicVSResources.Suggest_imports_for_types_in_NuGet_packages
Public ReadOnly Property Option_Add_missing_imports_on_paste As String =
BasicVSResources.Add_missing_imports_on_paste
Public ReadOnly Property Option_Regular_Expressions As String =
ServicesVSResources.Regular_Expressions
Public ReadOnly Property Option_Colorize_regular_expressions As String =
ServicesVSResources.Colorize_regular_expressions
Public ReadOnly Property Option_Report_invalid_regular_expressions As String =
ServicesVSResources.Report_invalid_regular_expressions
Public ReadOnly Property Option_Highlight_related_components_under_cursor As String =
ServicesVSResources.Highlight_related_components_under_cursor
Public ReadOnly Property Option_Show_completion_list As String =
ServicesVSResources.Show_completion_list
Public ReadOnly Property Option_Editor_Color_Scheme As String =
ServicesVSResources.Editor_Color_Scheme
Public ReadOnly Property Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page As String =
ServicesVSResources.Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page
Public ReadOnly Property Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations As String =
ServicesVSResources.Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations
Public ReadOnly Property Option_Color_Scheme_VisualStudio2019 As String =
ServicesVSResources.Visual_Studio_2019
Public ReadOnly Property Option_Color_Scheme_VisualStudio2017 As String =
ServicesVSResources.Visual_Studio_2017
Public ReadOnly Property Color_Scheme_VisualStudio2019_Tag As SchemeName =
SchemeName.VisualStudio2019
Public ReadOnly Property Color_Scheme_VisualStudio2017_Tag As SchemeName =
SchemeName.VisualStudio2017
Public ReadOnly Property Option_Show_Remove_Unused_References_command_in_Solution_Explorer_experimental As String =
ServicesVSResources.Show_Remove_Unused_References_command_in_Solution_Explorer_experimental
Public ReadOnly Property Enable_all_features_in_opened_files_from_source_generators_experimental As String =
ServicesVSResources.Enable_all_features_in_opened_files_from_source_generators_experimental
Public ReadOnly Property Option_Enable_file_logging_for_diagnostics As String =
ServicesVSResources.Enable_file_logging_for_diagnostics
Public ReadOnly Property Option_Skip_analyzers_for_implicitly_triggered_builds As String =
ServicesVSResources.Skip_analyzers_for_implicitly_triggered_builds
Public ReadOnly Property Show_inheritance_margin As String =
ServicesVSResources.Show_inheritance_margin
Public ReadOnly Property Combine_inheritance_margin_with_indicator_margin As String =
ServicesVSResources.Combine_inheritance_margin_with_indicator_margin
Public ReadOnly Property Inheritance_Margin As String = ServicesVSResources.Inheritance_Margin
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 Microsoft.CodeAnalysis.Editor.ColorSchemes
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.Options
Friend Module AdvancedOptionPageStrings
Public ReadOnly Property Option_AutomaticInsertionOfInterfaceAndMustOverrideMembers As String
Get
Return BasicVSResources.Automatic_insertion_of_Interface_and_MustOverride_members
End Get
End Property
Public ReadOnly Property Option_Analysis As String =
ServicesVSResources.Analysis
Public ReadOnly Property Option_Background_analysis_scope As String =
ServicesVSResources.Background_analysis_scope_colon
Public ReadOnly Property Option_Background_Analysis_Scope_Active_File As String =
ServicesVSResources.Current_document
Public ReadOnly Property Option_Background_Analysis_Scope_Open_Files_And_Projects As String =
ServicesVSResources.Open_documents
Public ReadOnly Property Option_Background_Analysis_Scope_Full_Solution As String =
ServicesVSResources.Entire_solution
Public ReadOnly Property Option_run_code_analysis_in_separate_process As String =
ServicesVSResources.Run_code_analysis_in_separate_process_requires_restart
Public ReadOnly Property Option_DisplayLineSeparators As String =
BasicVSResources.Show_procedure_line_separators
Public ReadOnly Property Option_Underline_reassigned_variables As String =
ServicesVSResources.Underline_reassigned_variables
Public ReadOnly Property Option_Display_all_hints_while_pressing_Alt_F1 As String =
ServicesVSResources.Display_all_hints_while_pressing_Alt_F1
Public ReadOnly Property Option_Color_hints As String =
ServicesVSResources.Color_hints
Public ReadOnly Property Option_Inline_Hints As String =
ServicesVSResources.Inline_Hints
Public ReadOnly Property Option_Display_inline_parameter_name_hints As String =
ServicesVSResources.Display_inline_parameter_name_hints
Public ReadOnly Property Option_Show_hints_for_literals As String =
ServicesVSResources.Show_hints_for_literals
Public ReadOnly Property Option_Show_hints_for_New_expressions As String =
BasicVSResources.Show_hints_for_New_expressions
Public ReadOnly Property Option_Show_hints_for_everything_else As String =
ServicesVSResources.Show_hints_for_everything_else
Public ReadOnly Property Option_Show_hints_for_indexers As String =
ServicesVSResources.Show_hints_for_indexers
Public ReadOnly Property Option_Suppress_hints_when_parameter_name_matches_the_method_s_intent As String =
ServicesVSResources.Suppress_hints_when_parameter_name_matches_the_method_s_intent
Public ReadOnly Property Option_Suppress_hints_when_parameter_names_differ_only_by_suffix As String =
ServicesVSResources.Suppress_hints_when_parameter_names_differ_only_by_suffix
Public ReadOnly Property Option_DontPutOutOrRefOnStruct As String =
BasicVSResources.Don_t_put_ByRef_on_custom_structure
Public ReadOnly Property Option_EditorHelp As String =
BasicVSResources.Editor_Help
Public ReadOnly Property Option_EnableEndConstruct As String =
BasicVSResources.A_utomatic_insertion_of_end_constructs
Public ReadOnly Property Option_EnableHighlightKeywords As String =
BasicVSResources.Highlight_related_keywords_under_cursor
Public ReadOnly Property Option_EnableHighlightReferences As String =
BasicVSResources.Highlight_references_to_symbol_under_cursor
Public ReadOnly Property Option_Quick_Actions As String =
ServicesVSResources.Quick_Actions
Public ReadOnly Property Option_Compute_Quick_Actions_asynchronously_experimental As String =
ServicesVSResources.Compute_Quick_Actions_asynchronously_experimental
Public ReadOnly Property Option_EnableLineCommit As String
Get
Return BasicVSResources.Pretty_listing_reformatting_of_code
End Get
End Property
Public ReadOnly Property Option_EnableOutlining As String
Get
Return BasicVSResources.Enter_outlining_mode_when_files_open
End Get
End Property
Public ReadOnly Property Option_ExtractMethod As String
Get
Return BasicVSResources.Extract_Method
End Get
End Property
Public ReadOnly Property Option_Implement_Interface_or_Abstract_Class As String =
ServicesVSResources.Implement_Interface_or_Abstract_Class
Public ReadOnly Property Option_When_inserting_properties_events_and_methods_place_them As String =
ServicesVSResources.When_inserting_properties_events_and_methods_place_them
Public ReadOnly Property Option_with_other_members_of_the_same_kind As String =
ServicesVSResources.with_other_members_of_the_same_kind
Public ReadOnly Property Option_When_generating_properties As String =
ServicesVSResources.When_generating_properties
Public ReadOnly Property Option_prefer_auto_properties As String =
ServicesVSResources.codegen_prefer_auto_properties
Public ReadOnly Property Option_prefer_throwing_properties As String =
ServicesVSResources.prefer_throwing_properties
Public ReadOnly Property Option_at_the_end As String =
ServicesVSResources.at_the_end
Public ReadOnly Property Option_GenerateXmlDocCommentsForTripleApostrophes As String =
BasicVSResources.Generate_XML_documentation_comments_for
Public ReadOnly Property Option_InsertApostropheAtTheStartOfNewLinesWhenWritingApostropheComments As String =
BasicVSResources.Insert_apostrophe_at_the_start_of_new_lines_when_writing_apostrophe_comments
Public ReadOnly Property Option_ShowRemarksInQuickInfo As String
Get
Return BasicVSResources.Show_remarks_in_Quick_Info
End Get
End Property
Public ReadOnly Property Option_GoToDefinition As String
Get
Return BasicVSResources.Go_to_Definition
End Get
End Property
Public ReadOnly Property Option_Highlighting As String
Get
Return BasicVSResources.Highlighting
End Get
End Property
Public ReadOnly Property Option_NavigateToObjectBrowser As String
Get
Return BasicVSResources.Navigate_to_Object_Browser_for_symbols_defined_in_metadata
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize As String
Get
Return BasicVSResources.Optimize_for_solution_size
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Small As String
Get
Return BasicVSResources.Small
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Regular As String
Get
Return BasicVSResources.Regular
End Get
End Property
Public ReadOnly Property Option_OptimizeForSolutionSize_Large As String
Get
Return BasicVSResources.Large
End Get
End Property
Public ReadOnly Property Option_Outlining As String = ServicesVSResources.Outlining
Public ReadOnly Property Option_Show_outlining_for_declaration_level_constructs As String =
ServicesVSResources.Show_outlining_for_declaration_level_constructs
Public ReadOnly Property Option_Show_outlining_for_code_level_constructs As String =
ServicesVSResources.Show_outlining_for_code_level_constructs
Public ReadOnly Property Option_Show_outlining_for_comments_and_preprocessor_regions As String =
ServicesVSResources.Show_outlining_for_comments_and_preprocessor_regions
Public ReadOnly Property Option_Collapse_regions_when_collapsing_to_definitions As String =
ServicesVSResources.Collapse_regions_when_collapsing_to_definitions
Public ReadOnly Property Option_Block_Structure_Guides As String =
ServicesVSResources.Block_Structure_Guides
Public ReadOnly Property Option_Comments As String =
ServicesVSResources.Comments
Public ReadOnly Property Option_Show_guides_for_declaration_level_constructs As String =
ServicesVSResources.Show_guides_for_declaration_level_constructs
Public ReadOnly Property Option_Show_guides_for_code_level_constructs As String =
ServicesVSResources.Show_guides_for_code_level_constructs
Public ReadOnly Property Option_Fading As String = ServicesVSResources.Fading
Public ReadOnly Property Option_Fade_out_unused_imports As String = BasicVSResources.Fade_out_unused_imports
Public ReadOnly Property Option_Performance As String
Get
Return BasicVSResources.Performance
End Get
End Property
Public ReadOnly Property Option_Report_invalid_placeholders_in_string_dot_format_calls As String
Get
Return BasicVSResources.Report_invalid_placeholders_in_string_dot_format_calls
End Get
End Property
Public ReadOnly Property Option_RenameTrackingPreview As String
Get
Return BasicVSResources.Show_preview_for_rename_tracking
End Get
End Property
Public ReadOnly Property Option_Import_Directives As String =
BasicVSResources.Import_Directives
Public ReadOnly Property Option_PlaceSystemNamespaceFirst As String =
BasicVSResources.Place_System_directives_first_when_sorting_imports
Public ReadOnly Property Option_SeparateImportGroups As String =
BasicVSResources.Separate_import_directive_groups
Public ReadOnly Property Option_Suggest_imports_for_types_in_reference_assemblies As String =
BasicVSResources.Suggest_imports_for_types_in_reference_assemblies
Public ReadOnly Property Option_Suggest_imports_for_types_in_NuGet_packages As String =
BasicVSResources.Suggest_imports_for_types_in_NuGet_packages
Public ReadOnly Property Option_Add_missing_imports_on_paste As String =
BasicVSResources.Add_missing_imports_on_paste
Public ReadOnly Property Option_Regular_Expressions As String =
ServicesVSResources.Regular_Expressions
Public ReadOnly Property Option_Colorize_regular_expressions As String =
ServicesVSResources.Colorize_regular_expressions
Public ReadOnly Property Option_Report_invalid_regular_expressions As String =
ServicesVSResources.Report_invalid_regular_expressions
Public ReadOnly Property Option_Highlight_related_components_under_cursor As String =
ServicesVSResources.Highlight_related_components_under_cursor
Public ReadOnly Property Option_Show_completion_list As String =
ServicesVSResources.Show_completion_list
Public ReadOnly Property Option_Editor_Color_Scheme As String =
ServicesVSResources.Editor_Color_Scheme
Public ReadOnly Property Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page As String =
ServicesVSResources.Editor_color_scheme_options_are_only_available_when_using_a_color_theme_bundled_with_Visual_Studio_The_color_theme_can_be_configured_from_the_Environment_General_options_page
Public ReadOnly Property Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations As String =
ServicesVSResources.Some_color_scheme_colors_are_being_overridden_by_changes_made_in_the_Environment_Fonts_and_Colors_options_page_Choose_Use_Defaults_in_the_Fonts_and_Colors_page_to_revert_all_customizations
Public ReadOnly Property Option_Color_Scheme_VisualStudio2019 As String =
ServicesVSResources.Visual_Studio_2019
Public ReadOnly Property Option_Color_Scheme_VisualStudio2017 As String =
ServicesVSResources.Visual_Studio_2017
Public ReadOnly Property Color_Scheme_VisualStudio2019_Tag As SchemeName =
SchemeName.VisualStudio2019
Public ReadOnly Property Color_Scheme_VisualStudio2017_Tag As SchemeName =
SchemeName.VisualStudio2017
Public ReadOnly Property Option_Show_Remove_Unused_References_command_in_Solution_Explorer_experimental As String =
ServicesVSResources.Show_Remove_Unused_References_command_in_Solution_Explorer_experimental
Public ReadOnly Property Enable_all_features_in_opened_files_from_source_generators_experimental As String =
ServicesVSResources.Enable_all_features_in_opened_files_from_source_generators_experimental
Public ReadOnly Property Option_Enable_file_logging_for_diagnostics As String =
ServicesVSResources.Enable_file_logging_for_diagnostics
Public ReadOnly Property Option_Skip_analyzers_for_implicitly_triggered_builds As String =
ServicesVSResources.Skip_analyzers_for_implicitly_triggered_builds
Public ReadOnly Property Show_inheritance_margin As String =
ServicesVSResources.Show_inheritance_margin
Public ReadOnly Property Combine_inheritance_margin_with_indicator_margin As String =
ServicesVSResources.Combine_inheritance_margin_with_indicator_margin
Public ReadOnly Property Inheritance_Margin As String = ServicesVSResources.Inheritance_Margin
End Module
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/EditorFeatures/CSharpTest/UseExpressionBody/Refactoring/UseExpressionBodyForIndexersRefactoringTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForIndexersRefactoringTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new UseExpressionBodyCodeRefactoringProvider();
private OptionsCollection UseExpressionBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement);
private OptionsCollection UseExpressionBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None));
private OptionsCollection UseBlockBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement);
private OptionsCollection UseBlockBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
{
await TestMissingAsync(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedInLambda()
{
await TestMissingAsync(
@"class C
{
Action Goo[int i]
{
get
{
return () => { [||] };
}
}
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
{
await TestMissingAsync(
@"class C
{
int this[int i] => [||]Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic));
}
[WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CodeRefactorings;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.UseExpressionBody;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseExpressionBody
{
public class UseExpressionBodyForIndexersRefactoringTests : AbstractCSharpCodeActionTest
{
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new UseExpressionBodyCodeRefactoringProvider();
private OptionsCollection UseExpressionBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.WhenPossibleWithSilentEnforcement);
private OptionsCollection UseExpressionBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.WhenPossible, NotificationOption2.None));
private OptionsCollection UseBlockBody =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, CSharpCodeStyleOptions.NeverWithSilentEnforcement);
private OptionsCollection UseBlockBodyDisabledDiagnostic =>
this.Option(CSharpCodeStyleOptions.PreferExpressionBodiedIndexers, new CodeStyleOption2<ExpressionBodyPreference>(ExpressionBodyPreference.Never, NotificationOption2.None));
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersExpressionBodiesAndInBlockBody()
{
await TestMissingAsync(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesWithoutDiagnosticAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseExpressionBodyDisabledDiagnostic));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesAndInBlockBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i]
{
get
{
[||]return Bar();
}
}
}",
@"class C
{
int this[int i] => Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedInLambda()
{
await TestMissingAsync(
@"class C
{
Action Goo[int i]
{
get
{
return () => { [||] };
}
}
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestNotOfferedIfUserPrefersBlockBodiesAndInExpressionBody()
{
await TestMissingAsync(
@"class C
{
int this[int i] => [||]Bar();
}", parameters: new TestParameters(options: UseBlockBody));
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersBlockBodiesWithoutDiagnosticAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseBlockBodyDisabledDiagnostic));
}
[WorkItem(20363, "https://github.com/dotnet/roslyn/issues/20363")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseExpressionBody)]
public async Task TestOfferedIfUserPrefersExpressionBodiesAndInExpressionBody()
{
await TestInRegularAndScript1Async(
@"class C
{
int this[int i] => [||]Bar();
}",
@"class C
{
int this[int i]
{
get
{
return Bar();
}
}
}", parameters: new TestParameters(options: UseExpressionBody));
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Analyzers/CSharp/CodeFixes/UseDefaultLiteral/CSharpUseDefaultLiteralCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseDefaultLiteral), Shared]
internal partial class CSharpUseDefaultLiteralCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseDefaultLiteralCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(IDEDiagnosticIds.UseDefaultLiteralDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
// Fix-All for this feature is somewhat complicated. Each time we fix one case, it
// may make the next case unfixable. For example:
//
// 'var v = x ? default(string) : default(string)'.
//
// Here, we can replace either of the default expressions, but not both. So we have
// to replace one at a time, and only actually replace if it's still safe to do so.
var parseOptions = (CSharpParseOptions)document.Project.ParseOptions;
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var preferSimpleDefaultExpression = document.Project.AnalyzerOptions.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, tree, cancellationToken).Value;
var workspace = document.Project.Solution.Workspace;
var originalRoot = editor.OriginalRoot;
var originalNodes = diagnostics.SelectAsArray(
d => (DefaultExpressionSyntax)originalRoot.FindNode(d.Location.SourceSpan, getInnermostNodeForTie: true));
await editor.ApplyExpressionLevelSemanticEditsAsync(
document, originalNodes,
(semanticModel, defaultExpression) => defaultExpression.CanReplaceWithDefaultLiteral(parseOptions, preferSimpleDefaultExpression, semanticModel, cancellationToken),
(_, currentRoot, defaultExpression) => currentRoot.ReplaceNode(
defaultExpression,
SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression).WithTriviaFrom(defaultExpression)),
cancellationToken).ConfigureAwait(false);
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Simplify_default_expression, createChangedDocument, CSharpAnalyzersResources.Simplify_default_expression)
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.UseDefaultLiteral
{
[ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseDefaultLiteral), Shared]
internal partial class CSharpUseDefaultLiteralCodeFixProvider : SyntaxEditorBasedCodeFixProvider
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpUseDefaultLiteralCodeFixProvider()
{
}
public override ImmutableArray<string> FixableDiagnosticIds { get; }
= ImmutableArray.Create(IDEDiagnosticIds.UseDefaultLiteralDiagnosticId);
internal sealed override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
context.RegisterCodeFix(new MyCodeAction(
c => FixAsync(context.Document, context.Diagnostics.First(), c)),
context.Diagnostics);
return Task.CompletedTask;
}
protected override async Task FixAllAsync(
Document document, ImmutableArray<Diagnostic> diagnostics,
SyntaxEditor editor, CancellationToken cancellationToken)
{
// Fix-All for this feature is somewhat complicated. Each time we fix one case, it
// may make the next case unfixable. For example:
//
// 'var v = x ? default(string) : default(string)'.
//
// Here, we can replace either of the default expressions, but not both. So we have
// to replace one at a time, and only actually replace if it's still safe to do so.
var parseOptions = (CSharpParseOptions)document.Project.ParseOptions;
var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
var preferSimpleDefaultExpression = document.Project.AnalyzerOptions.GetOption(CSharpCodeStyleOptions.PreferSimpleDefaultExpression, tree, cancellationToken).Value;
var workspace = document.Project.Solution.Workspace;
var originalRoot = editor.OriginalRoot;
var originalNodes = diagnostics.SelectAsArray(
d => (DefaultExpressionSyntax)originalRoot.FindNode(d.Location.SourceSpan, getInnermostNodeForTie: true));
await editor.ApplyExpressionLevelSemanticEditsAsync(
document, originalNodes,
(semanticModel, defaultExpression) => defaultExpression.CanReplaceWithDefaultLiteral(parseOptions, preferSimpleDefaultExpression, semanticModel, cancellationToken),
(_, currentRoot, defaultExpression) => currentRoot.ReplaceNode(
defaultExpression,
SyntaxFactory.LiteralExpression(SyntaxKind.DefaultLiteralExpression).WithTriviaFrom(defaultExpression)),
cancellationToken).ConfigureAwait(false);
}
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(CSharpAnalyzersResources.Simplify_default_expression, createChangedDocument, CSharpAnalyzersResources.Simplify_default_expression)
{
}
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Compilers/VisualBasic/Portable/Compilation/DocumentationComments/DocumentationCommentCompiler.Method.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Partial Friend Class DocumentationCommentCompiler
Inherits VisualBasicSymbolVisitor
Public Overrides Sub VisitMethod(symbol As MethodSymbol)
Me._cancellationToken.ThrowIfCancellationRequested()
If Not ShouldSkipSymbol(symbol) Then
Dim sourceMethod As SourceMethodSymbol =
If(TryCast(symbol, SourceMemberMethodSymbol),
DirectCast(TryCast(symbol, SourceDeclareMethodSymbol), SourceMethodSymbol))
If sourceMethod IsNot Nothing Then
WriteDocumentationCommentForMethod(sourceMethod)
End If
End If
End Sub
''' <returns> True, if the comment was written </returns>
Private Function WriteDocumentationCommentForMethod(method As SourceMethodSymbol) As Boolean
' NOTE: In UI scenarios, for partial methods Dev11 always uses implementation part's
' NOTE: comment if it exists ignoring errors, if any.
' NOTE:
' NOTE: In compilation scenarios Dev11 writes into resulting file *both* documentation
' NOTE: comments from declaration and implementation parts into separate <member></member> sections,
' NOTE: which seems to be wrong. If any part has error, it does not get into the final XML, thus
' NOTE: in case implementation part has errors and declaration part does not, the latest will
' NOTE: finally land in the resulting documentation, meaning that the user sees implementation
' NOTE: part's comment in UI and finds declaration part in the resulting XML.
' NOTE:
' NOTE: Roslyn for UI scenarios always (even in presence of errors) returns implementation part's
' NOTE: doc comment to be consistent with Dev11 and in compilation scenario writes implementation
' NOTE: part's comment if it exists and does not have errors, otherwise uses doc comment from
' NOTE: declaration part.
Dim implementationPart = TryCast(method.PartialImplementationPart, SourceMethodSymbol)
If implementationPart IsNot Nothing AndAlso WriteDocumentationCommentForMethod(implementationPart) Then
' We used comment from implementation part, that's all
Return True
End If
Dim docCommentTrivia As DocumentationCommentTriviaSyntax =
TryGetDocCommentTriviaAndGenerateDiagnostics(method.Syntax)
If docCommentTrivia Is Nothing Then
Return False
End If
Dim wellKnownElementNodes As New Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax))
Dim docCommentXml As String =
GetDocumentationCommentForSymbol(method, docCommentTrivia, wellKnownElementNodes)
' No further processing
If docCommentXml Is Nothing Then
FreeWellKnownElementNodes(wellKnownElementNodes)
Return False
End If
If docCommentTrivia.SyntaxTree.ReportDocumentationCommentDiagnostics OrElse _writer.IsSpecified Then
Dim symbolName As String = GetSymbolName(method)
' Duplicate top-level well known tags
ReportWarningsForDuplicatedTags(wellKnownElementNodes)
' <exception>
ReportWarningsForExceptionTags(wellKnownElementNodes)
' <returns>
If method.IsSub Then
If method.MethodKind = MethodKind.DeclareMethod Then
ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, ERRID.WRN_XMLDocReturnsOnADeclareSub, wellKnownElementNodes)
Else
ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, wellKnownElementNodes, symbolName)
End If
End If
' <param>
ReportWarningsForParamAndParamRefTags(wellKnownElementNodes, symbolName, method.Parameters)
' <value>
ReportIllegalWellKnownTagIfAny(WellKnownTag.Value, wellKnownElementNodes, symbolName)
' <typeparam>
If method.MethodKind = MethodKind.UserDefinedOperator OrElse method.MethodKind = MethodKind.DeclareMethod Then
ReportIllegalWellKnownTagIfAny(WellKnownTag.TypeParam, wellKnownElementNodes, symbolName)
Else
ReportWarningsForTypeParamTags(wellKnownElementNodes, symbolName, method.TypeParameters)
End If
' <typeparamref>
ReportWarningsForTypeParamRefTags(wellKnownElementNodes, symbolName, method, docCommentTrivia.SyntaxTree)
End If
FreeWellKnownElementNodes(wellKnownElementNodes)
WriteDocumentationCommentForSymbol(docCommentXml)
Return True
End Function
End Class
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System
Imports System.Collections.Generic
Imports System.Diagnostics
Imports System.Globalization
Imports System.IO
Imports System.Text
Imports System.Runtime.InteropServices
Imports System.Threading
Imports Microsoft.CodeAnalysis.Collections
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.VisualBasic
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Public Class VisualBasicCompilation
Partial Friend Class DocumentationCommentCompiler
Inherits VisualBasicSymbolVisitor
Public Overrides Sub VisitMethod(symbol As MethodSymbol)
Me._cancellationToken.ThrowIfCancellationRequested()
If Not ShouldSkipSymbol(symbol) Then
Dim sourceMethod As SourceMethodSymbol =
If(TryCast(symbol, SourceMemberMethodSymbol),
DirectCast(TryCast(symbol, SourceDeclareMethodSymbol), SourceMethodSymbol))
If sourceMethod IsNot Nothing Then
WriteDocumentationCommentForMethod(sourceMethod)
End If
End If
End Sub
''' <returns> True, if the comment was written </returns>
Private Function WriteDocumentationCommentForMethod(method As SourceMethodSymbol) As Boolean
' NOTE: In UI scenarios, for partial methods Dev11 always uses implementation part's
' NOTE: comment if it exists ignoring errors, if any.
' NOTE:
' NOTE: In compilation scenarios Dev11 writes into resulting file *both* documentation
' NOTE: comments from declaration and implementation parts into separate <member></member> sections,
' NOTE: which seems to be wrong. If any part has error, it does not get into the final XML, thus
' NOTE: in case implementation part has errors and declaration part does not, the latest will
' NOTE: finally land in the resulting documentation, meaning that the user sees implementation
' NOTE: part's comment in UI and finds declaration part in the resulting XML.
' NOTE:
' NOTE: Roslyn for UI scenarios always (even in presence of errors) returns implementation part's
' NOTE: doc comment to be consistent with Dev11 and in compilation scenario writes implementation
' NOTE: part's comment if it exists and does not have errors, otherwise uses doc comment from
' NOTE: declaration part.
Dim implementationPart = TryCast(method.PartialImplementationPart, SourceMethodSymbol)
If implementationPart IsNot Nothing AndAlso WriteDocumentationCommentForMethod(implementationPart) Then
' We used comment from implementation part, that's all
Return True
End If
Dim docCommentTrivia As DocumentationCommentTriviaSyntax =
TryGetDocCommentTriviaAndGenerateDiagnostics(method.Syntax)
If docCommentTrivia Is Nothing Then
Return False
End If
Dim wellKnownElementNodes As New Dictionary(Of WellKnownTag, ArrayBuilder(Of XmlNodeSyntax))
Dim docCommentXml As String =
GetDocumentationCommentForSymbol(method, docCommentTrivia, wellKnownElementNodes)
' No further processing
If docCommentXml Is Nothing Then
FreeWellKnownElementNodes(wellKnownElementNodes)
Return False
End If
If docCommentTrivia.SyntaxTree.ReportDocumentationCommentDiagnostics OrElse _writer.IsSpecified Then
Dim symbolName As String = GetSymbolName(method)
' Duplicate top-level well known tags
ReportWarningsForDuplicatedTags(wellKnownElementNodes)
' <exception>
ReportWarningsForExceptionTags(wellKnownElementNodes)
' <returns>
If method.IsSub Then
If method.MethodKind = MethodKind.DeclareMethod Then
ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, ERRID.WRN_XMLDocReturnsOnADeclareSub, wellKnownElementNodes)
Else
ReportIllegalWellKnownTagIfAny(WellKnownTag.Returns, wellKnownElementNodes, symbolName)
End If
End If
' <param>
ReportWarningsForParamAndParamRefTags(wellKnownElementNodes, symbolName, method.Parameters)
' <value>
ReportIllegalWellKnownTagIfAny(WellKnownTag.Value, wellKnownElementNodes, symbolName)
' <typeparam>
If method.MethodKind = MethodKind.UserDefinedOperator OrElse method.MethodKind = MethodKind.DeclareMethod Then
ReportIllegalWellKnownTagIfAny(WellKnownTag.TypeParam, wellKnownElementNodes, symbolName)
Else
ReportWarningsForTypeParamTags(wellKnownElementNodes, symbolName, method.TypeParameters)
End If
' <typeparamref>
ReportWarningsForTypeParamRefTags(wellKnownElementNodes, symbolName, method, docCommentTrivia.SyntaxTree)
End If
FreeWellKnownElementNodes(wellKnownElementNodes)
WriteDocumentationCommentForSymbol(docCommentXml)
Return True
End Function
End Class
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/Features/Core/Portable/CodeFixes/CodeFixService.FixAllPredefinedDiagnosticProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal partial class CodeFixService
{
private class FixAllPredefinedDiagnosticProvider : FixAllContext.DiagnosticProvider
{
private readonly ImmutableArray<Diagnostic> _diagnostics;
public FixAllPredefinedDiagnosticProvider(ImmutableArray<Diagnostic> diagnostics)
=> _diagnostics = diagnostics;
public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics);
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics);
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<Diagnostic>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CodeFixes
{
internal partial class CodeFixService
{
private class FixAllPredefinedDiagnosticProvider : FixAllContext.DiagnosticProvider
{
private readonly ImmutableArray<Diagnostic> _diagnostics;
public FixAllPredefinedDiagnosticProvider(ImmutableArray<Diagnostic> diagnostics)
=> _diagnostics = diagnostics;
public override Task<IEnumerable<Diagnostic>> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics);
public override Task<IEnumerable<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken)
=> Task.FromResult<IEnumerable<Diagnostic>>(_diagnostics);
public override Task<IEnumerable<Diagnostic>> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<Diagnostic>();
}
}
}
| -1 |
dotnet/roslyn | 56,090 | Disallow converting a lambda with attributes to an expression tree. | Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | AlekseyTs | "2021-09-01T21:52:53Z" | "2021-09-02T12:51:31Z" | a835dd858e7472a7598e4275ed014a90d13fc0a0 | f16180767deec9090bf478a7e0516e92fb3dd723 | Disallow converting a lambda with attributes to an expression tree.. Closes #53910.
Relates to test plan https://github.com/dotnet/roslyn/issues/52192 | ./src/VisualStudio/VisualBasic/Impl/CodeModel/Extenders/GenericExtender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
<ComVisible(True)>
<ComDefaultInterface(GetType(IVBGenericExtender))>
Public Class GenericExtender
Implements IVBGenericExtender
Friend Shared Function Create(codeType As AbstractCodeType) As IVBGenericExtender
Dim result = New GenericExtender(codeType)
Return CType(ComAggregate.CreateAggregatedObject(result), IVBGenericExtender)
End Function
Private ReadOnly _codeType As ParentHandle(Of AbstractCodeType)
Private Sub New(codeType As AbstractCodeType)
_codeType = New ParentHandle(Of AbstractCodeType)(codeType)
End Sub
Private Function GetTypesCount(baseType As Boolean) As Integer
Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol)
If baseType Then
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Module,
TypeKind.Structure,
TypeKind.Delegate,
TypeKind.Enum
Return 1
Case TypeKind.Interface
Return typeSymbol.Interfaces.Length
End Select
Else
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Structure
Return typeSymbol.Interfaces.Length
End Select
End If
Throw Exceptions.ThrowEInvalidArg()
End Function
Private Function GetGenericName(baseType As Boolean, index As Integer) As String
Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol)
If baseType Then
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Module,
TypeKind.Structure,
TypeKind.Delegate,
TypeKind.Enum
If index = 0 Then
Dim baseTypeSymbol = typeSymbol.BaseType
If baseTypeSymbol IsNot Nothing Then
Return baseTypeSymbol.ToDisplayString()
End If
End If
Return Nothing
Case TypeKind.Interface
Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length,
typeSymbol.Interfaces(index).ToDisplayString(),
Nothing)
End Select
Else
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Structure
Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length,
typeSymbol.Interfaces(index).ToDisplayString(),
Nothing)
Case TypeKind.Delegate,
TypeKind.Enum
Return Nothing
End Select
End If
Throw Exceptions.ThrowEInvalidArg()
End Function
Public ReadOnly Property GetBaseGenericName(index As Integer) As String Implements IVBGenericExtender.GetBaseGenericName
Get
' NOTE: index is 1-based.
Return GetGenericName(baseType:=True, index:=index - 1)
End Get
End Property
Public ReadOnly Property GetBaseTypesCount As Integer Implements IVBGenericExtender.GetBaseTypesCount
Get
Return GetTypesCount(baseType:=True)
End Get
End Property
Public ReadOnly Property GetImplementedTypesCount As Integer Implements IVBGenericExtender.GetImplementedTypesCount
Get
Return GetTypesCount(baseType:=False)
End Get
End Property
Public ReadOnly Property GetImplTypeGenericName(index As Integer) As String Implements IVBGenericExtender.GetImplTypeGenericName
Get
' NOTE: index is 1-based.
Return GetGenericName(baseType:=False, index:=index - 1)
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Runtime.InteropServices
Imports Microsoft.CodeAnalysis
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
Imports Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Interop
Imports Microsoft.VisualStudio.LanguageServices.Implementation.Utilities
Imports Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Interop
Imports TypeKind = Microsoft.CodeAnalysis.TypeKind
Namespace Microsoft.VisualStudio.LanguageServices.VisualBasic.CodeModel.Extenders
<ComVisible(True)>
<ComDefaultInterface(GetType(IVBGenericExtender))>
Public Class GenericExtender
Implements IVBGenericExtender
Friend Shared Function Create(codeType As AbstractCodeType) As IVBGenericExtender
Dim result = New GenericExtender(codeType)
Return CType(ComAggregate.CreateAggregatedObject(result), IVBGenericExtender)
End Function
Private ReadOnly _codeType As ParentHandle(Of AbstractCodeType)
Private Sub New(codeType As AbstractCodeType)
_codeType = New ParentHandle(Of AbstractCodeType)(codeType)
End Sub
Private Function GetTypesCount(baseType As Boolean) As Integer
Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol)
If baseType Then
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Module,
TypeKind.Structure,
TypeKind.Delegate,
TypeKind.Enum
Return 1
Case TypeKind.Interface
Return typeSymbol.Interfaces.Length
End Select
Else
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Structure
Return typeSymbol.Interfaces.Length
End Select
End If
Throw Exceptions.ThrowEInvalidArg()
End Function
Private Function GetGenericName(baseType As Boolean, index As Integer) As String
Dim typeSymbol = CType(_codeType.Value.LookupTypeSymbol(), INamedTypeSymbol)
If baseType Then
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Module,
TypeKind.Structure,
TypeKind.Delegate,
TypeKind.Enum
If index = 0 Then
Dim baseTypeSymbol = typeSymbol.BaseType
If baseTypeSymbol IsNot Nothing Then
Return baseTypeSymbol.ToDisplayString()
End If
End If
Return Nothing
Case TypeKind.Interface
Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length,
typeSymbol.Interfaces(index).ToDisplayString(),
Nothing)
End Select
Else
Select Case typeSymbol.TypeKind
Case TypeKind.Class,
TypeKind.Structure
Return If(index >= 0 AndAlso index < typeSymbol.Interfaces.Length,
typeSymbol.Interfaces(index).ToDisplayString(),
Nothing)
Case TypeKind.Delegate,
TypeKind.Enum
Return Nothing
End Select
End If
Throw Exceptions.ThrowEInvalidArg()
End Function
Public ReadOnly Property GetBaseGenericName(index As Integer) As String Implements IVBGenericExtender.GetBaseGenericName
Get
' NOTE: index is 1-based.
Return GetGenericName(baseType:=True, index:=index - 1)
End Get
End Property
Public ReadOnly Property GetBaseTypesCount As Integer Implements IVBGenericExtender.GetBaseTypesCount
Get
Return GetTypesCount(baseType:=True)
End Get
End Property
Public ReadOnly Property GetImplementedTypesCount As Integer Implements IVBGenericExtender.GetImplementedTypesCount
Get
Return GetTypesCount(baseType:=False)
End Get
End Property
Public ReadOnly Property GetImplTypeGenericName(index As Integer) As String Implements IVBGenericExtender.GetImplTypeGenericName
Get
' NOTE: index is 1-based.
Return GetGenericName(baseType:=False, index:=index - 1)
End Get
End Property
End Class
End Namespace
| -1 |
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/CSharpTest/CodeActions/Preview/PreviewTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings
{
public partial class PreviewTests : AbstractCSharpCodeActionTest
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf
.AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService))
.AddParts(
typeof(MockDiagnosticUpdateSourceRegistrationService),
typeof(MockPreviewPaneService));
private const string AddedDocumentName = "AddedDocument";
private const string AddedDocumentText = "class C1 {}";
private static string s_removedMetadataReferenceDisplayName = "";
private const string AddedProjectName = "AddedProject";
private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId();
private const string ChangedDocumentText = "class C {}";
protected override TestComposition GetComposition() => s_composition;
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new MyCodeRefactoringProvider();
private class MyCodeRefactoringProvider : CodeRefactoringProvider
{
public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var codeAction = new MyCodeAction(context.Document);
context.RegisterRefactoring(codeAction, context.Span);
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction
{
private readonly Document _oldDocument;
public MyCodeAction(Document document)
=> _oldDocument = document;
public override string Title
{
get
{
return "Title";
}
}
protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
var solution = _oldDocument.Project.Solution;
// Add a document - This will result in IWpfTextView previews.
solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText);
// Remove a reference - This will result in a string preview.
var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1];
s_removedMetadataReferenceDisplayName = removedReference.Display;
solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference);
// Add a project - This will result in a string preview.
solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp));
// Change a document - This will result in IWpfTextView previews.
solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken));
return Task.FromResult(solution);
}
}
}
private void GetMainDocumentAndPreviews(TestParameters parameters, TestWorkspace workspace, out Document document, out SolutionPreviewResult previews)
{
document = GetDocument(workspace);
var provider = CreateCodeRefactoringProvider(workspace, parameters);
var span = document.GetSyntaxRootAsync().Result.Span;
var refactorings = new List<CodeAction>();
var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
var action = refactorings.Single();
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
previews = editHandler.GetPreviews(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")]
public async Task TestPickTheRightPreview_NoPreference()
{
var parameters = new TestParameters();
using var workspace = CreateWorkspaceFromOptions("class D {}", parameters);
GetMainDocumentAndPreviews(parameters, workspace, out var document, out var previews);
// The changed document comes first.
var previewObjects = await previews.GetPreviewsAsync();
var preview = previewObjects[0];
Assert.NotNull(preview);
Assert.True(preview is DifferenceViewerPreview);
var diffView = preview as DifferenceViewerPreview;
var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
Assert.Equal(ChangedDocumentText, text);
diffView.Dispose();
// Then comes the removed metadata reference.
preview = previewObjects[1];
Assert.NotNull(preview);
Assert.True(preview is string);
text = preview as string;
Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal);
// And finally the added project.
preview = previewObjects[2];
Assert.NotNull(preview);
Assert.True(preview is string);
text = preview as string;
Assert.Contains(AddedProjectName, text, StringComparison.Ordinal);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Test.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings
{
public partial class PreviewTests : AbstractCSharpCodeActionTest
{
private static readonly TestComposition s_composition = EditorTestCompositions.EditorFeaturesWpf
.AddExcludedPartTypes(typeof(IDiagnosticUpdateSourceRegistrationService))
.AddParts(
typeof(MockDiagnosticUpdateSourceRegistrationService),
typeof(MockPreviewPaneService));
private const string AddedDocumentName = "AddedDocument";
private const string AddedDocumentText = "class C1 {}";
private static string s_removedMetadataReferenceDisplayName = "";
private const string AddedProjectName = "AddedProject";
private static readonly ProjectId s_addedProjectId = ProjectId.CreateNewId();
private const string ChangedDocumentText = "class C {}";
protected override TestComposition GetComposition() => s_composition;
protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters)
=> new MyCodeRefactoringProvider();
private class MyCodeRefactoringProvider : CodeRefactoringProvider
{
public sealed override Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var codeAction = new MyCodeAction(context.Document);
context.RegisterRefactoring(codeAction, context.Span);
return Task.CompletedTask;
}
private class MyCodeAction : CodeAction
{
private readonly Document _oldDocument;
public MyCodeAction(Document document)
=> _oldDocument = document;
public override string Title
{
get
{
return "Title";
}
}
protected override Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
var solution = _oldDocument.Project.Solution;
// Add a document - This will result in IWpfTextView previews.
solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, AddedDocumentName), AddedDocumentName, AddedDocumentText);
// Remove a reference - This will result in a string preview.
var removedReference = _oldDocument.Project.MetadataReferences[_oldDocument.Project.MetadataReferences.Count - 1];
s_removedMetadataReferenceDisplayName = removedReference.Display;
solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference);
// Add a project - This will result in a string preview.
solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), AddedProjectName, AddedProjectName, LanguageNames.CSharp));
// Change a document - This will result in IWpfTextView previews.
solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, CSharpSyntaxTree.ParseText(ChangedDocumentText, cancellationToken: cancellationToken).GetRoot(cancellationToken));
return Task.FromResult(solution);
}
}
}
private async Task<(Document document, SolutionPreviewResult previews)> GetMainDocumentAndPreviewsAsync(TestParameters parameters, TestWorkspace workspace)
{
var document = GetDocument(workspace);
var provider = CreateCodeRefactoringProvider(workspace, parameters);
var span = document.GetSyntaxRootAsync().Result.Span;
var refactorings = new List<CodeAction>();
var context = new CodeRefactoringContext(document, span, refactorings.Add, CancellationToken.None);
provider.ComputeRefactoringsAsync(context).Wait();
var action = refactorings.Single();
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var previews = await editHandler.GetPreviewsAsync(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None);
return (document, previews);
}
[WpfFact(Skip = "https://github.com/dotnet/roslyn/issues/14421")]
public async Task TestPickTheRightPreview_NoPreference()
{
var parameters = new TestParameters();
using var workspace = CreateWorkspaceFromOptions("class D {}", parameters);
var (document, previews) = await GetMainDocumentAndPreviewsAsync(parameters, workspace);
// The changed document comes first.
var previewObjects = await previews.GetPreviewsAsync();
var preview = previewObjects[0];
Assert.NotNull(preview);
Assert.True(preview is DifferenceViewerPreview);
var diffView = preview as DifferenceViewerPreview;
var text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
Assert.Equal(ChangedDocumentText, text);
diffView.Dispose();
// Then comes the removed metadata reference.
preview = previewObjects[1];
Assert.NotNull(preview);
Assert.True(preview is string);
text = preview as string;
Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal);
// And finally the added project.
preview = previewObjects[2];
Assert.NotNull(preview);
Assert.True(preview is string);
text = preview as string;
Assert.Contains(AddedProjectName, text, StringComparison.Ordinal);
}
}
}
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/SuggestedAction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Threading;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Base class for all Roslyn light bulb menu items.
/// </summary>
internal abstract partial class SuggestedAction : ForegroundThreadAffinitizedObject, ISuggestedAction3, IEquatable<ISuggestedAction>
{
protected readonly SuggestedActionsSourceProvider SourceProvider;
protected readonly Workspace Workspace;
protected readonly ITextBuffer SubjectBuffer;
protected readonly object Provider;
internal readonly CodeAction CodeAction;
private bool _isApplied;
private ICodeActionEditHandlerService EditHandler => SourceProvider.EditHandler;
internal SuggestedAction(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider,
Workspace workspace,
ITextBuffer subjectBuffer,
object provider,
CodeAction codeAction)
: base(threadingContext)
{
Contract.ThrowIfNull(provider);
Contract.ThrowIfNull(codeAction);
SourceProvider = sourceProvider;
Workspace = workspace;
SubjectBuffer = subjectBuffer;
Provider = provider;
CodeAction = codeAction;
}
internal virtual CodeActionPriority Priority => CodeAction.Priority;
internal bool IsForCodeQualityImprovement
=> (Provider as SyntaxEditorBasedCodeFixProvider)?.CodeFixCategory == CodeFixCategory.CodeQuality;
public virtual bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = CodeAction.GetType().GetTelemetryId();
return true;
}
// NOTE: We want to avoid computing the operations on the UI thread. So we use Task.Run() to do this work on the background thread.
protected Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
return Task.Run(
() => CodeAction.GetOperationsAsync(progressTracker, cancellationToken), cancellationToken);
}
protected static Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(CodeActionWithOptions actionWithOptions, object options, CancellationToken cancellationToken)
{
return Task.Run(
() => actionWithOptions.GetOperationsAsync(options, cancellationToken), cancellationToken);
}
protected Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken)
{
return Task.Run(
() => CodeAction.GetPreviewOperationsAsync(cancellationToken), cancellationToken);
}
public void Invoke(CancellationToken cancellationToken)
{
SourceProvider.UIThreadOperationExecutor.Execute(CodeAction.Title, CodeAction.Message, allowCancellation: true, showProgress: true, action: context =>
{
// If we want to report progress, we need to create a scope inside the context -- the main context itself doesn't have a way
// to report progress. We pass the same allow cancellation and message so otherwise nothing changes.
using var scope = context.AddScope(allowCancellation: true, CodeAction.Message);
using var combinedCancellationToken = cancellationToken.CombineWith(context.UserCancellationToken);
Invoke(new UIThreadOperationContextProgressTracker(scope), combinedCancellationToken.Token);
});
}
public void Invoke(IUIThreadOperationContext context)
{
using var scope = context.AddScope(allowCancellation: true, CodeAction.Message);
this.Invoke(new UIThreadOperationContextProgressTracker(scope), context.UserCancellationToken);
}
private void Invoke(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
// While we're not technically doing anything async here, we need to let the
// integration test harness know that it should not proceed until all this
// work is done. Otherwise it might ask to do some work before we finish.
// That can happen because although we're on the UI thread, we may do things
// that end up causing VS to pump the messages that the test harness enqueues
// to the UI thread as well.
using (SourceProvider.OperationListener.BeginAsyncOperation($"{nameof(SuggestedAction)}.{nameof(Invoke)}"))
{
InnerInvoke(progressTracker, cancellationToken);
}
}
protected virtual void InnerInvoke(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
AssertIsForeground();
var snapshot = SubjectBuffer.CurrentSnapshot;
using (new CaretPositionRestorer(SubjectBuffer, EditHandler.AssociatedViewService))
{
Document getFromDocument() => SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
InvokeCore(getFromDocument, progressTracker, cancellationToken);
}
}
protected void InvokeCore(
Func<Document> getFromDocument, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
AssertIsForeground();
var extensionManager = Workspace.Services.GetService<IExtensionManager>();
extensionManager.PerformAction(Provider, () =>
{
InvokeWorker(getFromDocument, progressTracker, cancellationToken);
});
}
private void InvokeWorker(
Func<Document> getFromDocument, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
AssertIsForeground();
IEnumerable<CodeActionOperation> operations = null;
if (CodeAction is CodeActionWithOptions actionWithOptions)
{
var options = actionWithOptions.GetOptions(cancellationToken);
if (options != null)
{
// Note: we want to block the UI thread here so the user cannot modify anything while the codefix applies
operations = GetOperationsAsync(actionWithOptions, options, cancellationToken).WaitAndGetResult(cancellationToken);
}
}
else
{
// Note: we want to block the UI thread here so the user cannot modify anything while the codefix applies
operations = GetOperationsAsync(progressTracker, cancellationToken).WaitAndGetResult(cancellationToken);
}
if (operations != null)
{
// Clear the progress we showed while computing the action.
// We'll now show progress as we apply the action.
progressTracker.Clear();
using (Logger.LogBlock(
FunctionId.CodeFixes_ApplyChanges, KeyValueLogMessage.Create(LogType.UserAction, m => CreateLogProperties(m)), cancellationToken))
{
// Note: we want to block the UI thread here so the user cannot modify anything while the codefix applies
_isApplied = EditHandler.Apply(Workspace, getFromDocument(),
operations.ToImmutableArray(), CodeAction.Title,
progressTracker, cancellationToken);
}
}
}
private void CreateLogProperties(Dictionary<string, object> map)
{
// set various correlation info
if (CodeAction is FixSomeCodeAction fixSome)
{
// fix all correlation info
map[FixAllLogger.CorrelationId] = fixSome.FixAllState.CorrelationId;
map[FixAllLogger.FixAllScope] = fixSome.FixAllState.Scope.ToString();
}
if (TryGetTelemetryId(out var telemetryId))
{
// Lightbulb correlation info
map["TelemetryId"] = telemetryId.ToString();
}
if (this is ITelemetryDiagnosticID<string> diagnosticId)
{
// save what it is actually fixing
map["DiagnosticId"] = diagnosticId.GetDiagnosticID();
}
}
public string DisplayText
{
get
{
// Underscores will become an accelerator in the VS smart tag. So we double all
// underscores so they actually get represented as an underscore in the UI.
var extensionManager = Workspace.Services.GetService<IExtensionManager>();
var text = extensionManager.PerformFunction(Provider, () => CodeAction.Title, defaultValue: string.Empty);
return text.Replace("_", "__");
}
}
public string DisplayTextSuffix => "";
protected async Task<SolutionPreviewResult> GetPreviewResultAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// We will always invoke this from the UI thread.
AssertIsForeground();
// We use ConfigureAwait(true) to stay on the UI thread.
var operations = await GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(true);
return EditHandler.GetPreviews(Workspace, operations, cancellationToken);
}
public virtual bool HasPreview => false;
public virtual Task<object> GetPreviewAsync(CancellationToken cancellationToken)
=> SpecializedTasks.Null<object>();
public virtual bool HasActionSets => false;
public virtual Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<SuggestedActionSet>();
#region not supported
void IDisposable.Dispose()
{
// do nothing
}
// same as display text
string ISuggestedAction.IconAutomationText => DisplayText;
ImageMoniker ISuggestedAction.IconMoniker
{
get
{
var tags = CodeAction.Tags;
if (tags.Length > 0)
{
foreach (var service in SourceProvider.ImageIdServices)
{
if (service.Value.TryGetImageId(tags, out var imageId) && !imageId.Equals(default(ImageId)))
{
// Not using the extension method because it's not available in Cocoa
return new ImageMoniker
{
Guid = imageId.Guid,
Id = imageId.Id
};
}
}
}
return default;
}
}
// no shortcut support
string ISuggestedAction.InputGestureText => null;
#endregion
#region IEquatable<ISuggestedAction>
public bool Equals(ISuggestedAction other)
=> Equals(other as SuggestedAction);
public override bool Equals(object obj)
=> Equals(obj as SuggestedAction);
internal bool Equals(SuggestedAction otherSuggestedAction)
{
if (otherSuggestedAction == null)
{
return false;
}
if (this == otherSuggestedAction)
{
return true;
}
if (Provider != otherSuggestedAction.Provider)
{
return false;
}
var otherCodeAction = otherSuggestedAction.CodeAction;
if (CodeAction.EquivalenceKey == null || otherCodeAction.EquivalenceKey == null)
{
return false;
}
return CodeAction.EquivalenceKey == otherCodeAction.EquivalenceKey;
}
public override int GetHashCode()
{
if (CodeAction.EquivalenceKey == null)
{
return base.GetHashCode();
}
return Hash.Combine(Provider.GetHashCode(), CodeAction.EquivalenceKey.GetHashCode());
}
#endregion
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly SuggestedAction _suggestedAction;
public TestAccessor(SuggestedAction suggestedAction)
=> _suggestedAction = suggestedAction;
public ref bool IsApplied => ref _suggestedAction._isApplied;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Extensions;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Core.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Threading;
using Microsoft.VisualStudio.Utilities;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions
{
/// <summary>
/// Base class for all Roslyn light bulb menu items.
/// </summary>
internal abstract partial class SuggestedAction : ForegroundThreadAffinitizedObject, ISuggestedAction3, IEquatable<ISuggestedAction>
{
protected readonly SuggestedActionsSourceProvider SourceProvider;
protected readonly Workspace Workspace;
protected readonly ITextBuffer SubjectBuffer;
protected readonly object Provider;
internal readonly CodeAction CodeAction;
private bool _isApplied;
private ICodeActionEditHandlerService EditHandler => SourceProvider.EditHandler;
internal SuggestedAction(
IThreadingContext threadingContext,
SuggestedActionsSourceProvider sourceProvider,
Workspace workspace,
ITextBuffer subjectBuffer,
object provider,
CodeAction codeAction)
: base(threadingContext)
{
Contract.ThrowIfNull(provider);
Contract.ThrowIfNull(codeAction);
SourceProvider = sourceProvider;
Workspace = workspace;
SubjectBuffer = subjectBuffer;
Provider = provider;
CodeAction = codeAction;
}
internal virtual CodeActionPriority Priority => CodeAction.Priority;
internal bool IsForCodeQualityImprovement
=> (Provider as SyntaxEditorBasedCodeFixProvider)?.CodeFixCategory == CodeFixCategory.CodeQuality;
public virtual bool TryGetTelemetryId(out Guid telemetryId)
{
telemetryId = CodeAction.GetType().GetTelemetryId();
return true;
}
// NOTE: We want to avoid computing the operations on the UI thread. So we use Task.Run() to do this work on the background thread.
protected Task<ImmutableArray<CodeActionOperation>> GetOperationsAsync(
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
return Task.Run(
() => CodeAction.GetOperationsAsync(progressTracker, cancellationToken), cancellationToken);
}
protected static Task<IEnumerable<CodeActionOperation>> GetOperationsAsync(CodeActionWithOptions actionWithOptions, object options, CancellationToken cancellationToken)
{
return Task.Run(
() => actionWithOptions.GetOperationsAsync(options, cancellationToken), cancellationToken);
}
protected Task<ImmutableArray<CodeActionOperation>> GetPreviewOperationsAsync(CancellationToken cancellationToken)
{
return Task.Run(
() => CodeAction.GetPreviewOperationsAsync(cancellationToken), cancellationToken);
}
public void Invoke(CancellationToken cancellationToken)
{
SourceProvider.UIThreadOperationExecutor.Execute(CodeAction.Title, CodeAction.Message, allowCancellation: true, showProgress: true, action: context =>
{
// If we want to report progress, we need to create a scope inside the context -- the main context itself doesn't have a way
// to report progress. We pass the same allow cancellation and message so otherwise nothing changes.
using var scope = context.AddScope(allowCancellation: true, CodeAction.Message);
using var combinedCancellationToken = cancellationToken.CombineWith(context.UserCancellationToken);
Invoke(new UIThreadOperationContextProgressTracker(scope), combinedCancellationToken.Token);
});
}
public void Invoke(IUIThreadOperationContext context)
{
using var scope = context.AddScope(allowCancellation: true, CodeAction.Message);
this.Invoke(new UIThreadOperationContextProgressTracker(scope), context.UserCancellationToken);
}
private void Invoke(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
// While we're not technically doing anything async here, we need to let the
// integration test harness know that it should not proceed until all this
// work is done. Otherwise it might ask to do some work before we finish.
// That can happen because although we're on the UI thread, we may do things
// that end up causing VS to pump the messages that the test harness enqueues
// to the UI thread as well.
using (SourceProvider.OperationListener.BeginAsyncOperation($"{nameof(SuggestedAction)}.{nameof(Invoke)}"))
{
InnerInvoke(progressTracker, cancellationToken);
}
}
protected virtual void InnerInvoke(IProgressTracker progressTracker, CancellationToken cancellationToken)
{
AssertIsForeground();
var snapshot = SubjectBuffer.CurrentSnapshot;
using (new CaretPositionRestorer(SubjectBuffer, EditHandler.AssociatedViewService))
{
Document getFromDocument() => SubjectBuffer.CurrentSnapshot.GetOpenDocumentInCurrentContextWithChanges();
InvokeCore(getFromDocument, progressTracker, cancellationToken);
}
}
protected void InvokeCore(
Func<Document> getFromDocument, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
AssertIsForeground();
var extensionManager = Workspace.Services.GetService<IExtensionManager>();
extensionManager.PerformAction(Provider, () =>
{
InvokeWorker(getFromDocument, progressTracker, cancellationToken);
});
}
private void InvokeWorker(
Func<Document> getFromDocument, IProgressTracker progressTracker, CancellationToken cancellationToken)
{
AssertIsForeground();
IEnumerable<CodeActionOperation> operations = null;
if (CodeAction is CodeActionWithOptions actionWithOptions)
{
var options = actionWithOptions.GetOptions(cancellationToken);
if (options != null)
{
// Note: we want to block the UI thread here so the user cannot modify anything while the codefix applies
operations = GetOperationsAsync(actionWithOptions, options, cancellationToken).WaitAndGetResult(cancellationToken);
}
}
else
{
// Note: we want to block the UI thread here so the user cannot modify anything while the codefix applies
operations = GetOperationsAsync(progressTracker, cancellationToken).WaitAndGetResult(cancellationToken);
}
if (operations != null)
{
// Clear the progress we showed while computing the action.
// We'll now show progress as we apply the action.
progressTracker.Clear();
using (Logger.LogBlock(
FunctionId.CodeFixes_ApplyChanges, KeyValueLogMessage.Create(LogType.UserAction, m => CreateLogProperties(m)), cancellationToken))
{
// Note: we want to block the UI thread here so the user cannot modify anything while the codefix applies
_isApplied = EditHandler.Apply(Workspace, getFromDocument(),
operations.ToImmutableArray(), CodeAction.Title,
progressTracker, cancellationToken);
}
}
}
private void CreateLogProperties(Dictionary<string, object> map)
{
// set various correlation info
if (CodeAction is FixSomeCodeAction fixSome)
{
// fix all correlation info
map[FixAllLogger.CorrelationId] = fixSome.FixAllState.CorrelationId;
map[FixAllLogger.FixAllScope] = fixSome.FixAllState.Scope.ToString();
}
if (TryGetTelemetryId(out var telemetryId))
{
// Lightbulb correlation info
map["TelemetryId"] = telemetryId.ToString();
}
if (this is ITelemetryDiagnosticID<string> diagnosticId)
{
// save what it is actually fixing
map["DiagnosticId"] = diagnosticId.GetDiagnosticID();
}
}
public string DisplayText
{
get
{
// Underscores will become an accelerator in the VS smart tag. So we double all
// underscores so they actually get represented as an underscore in the UI.
var extensionManager = Workspace.Services.GetService<IExtensionManager>();
var text = extensionManager.PerformFunction(Provider, () => CodeAction.Title, defaultValue: string.Empty);
return text.Replace("_", "__");
}
}
public string DisplayTextSuffix => "";
protected async Task<SolutionPreviewResult> GetPreviewResultAsync(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// We will always invoke this from the UI thread.
AssertIsForeground();
// We use ConfigureAwait(true) to stay on the UI thread.
var operations = await GetPreviewOperationsAsync(cancellationToken).ConfigureAwait(true);
return await EditHandler.GetPreviewsAsync(Workspace, operations, cancellationToken).ConfigureAwait(true);
}
public virtual bool HasPreview => false;
public virtual Task<object> GetPreviewAsync(CancellationToken cancellationToken)
=> SpecializedTasks.Null<object>();
public virtual bool HasActionSets => false;
public virtual Task<IEnumerable<SuggestedActionSet>> GetActionSetsAsync(CancellationToken cancellationToken)
=> SpecializedTasks.EmptyEnumerable<SuggestedActionSet>();
#region not supported
void IDisposable.Dispose()
{
// do nothing
}
// same as display text
string ISuggestedAction.IconAutomationText => DisplayText;
ImageMoniker ISuggestedAction.IconMoniker
{
get
{
var tags = CodeAction.Tags;
if (tags.Length > 0)
{
foreach (var service in SourceProvider.ImageIdServices)
{
if (service.Value.TryGetImageId(tags, out var imageId) && !imageId.Equals(default(ImageId)))
{
// Not using the extension method because it's not available in Cocoa
return new ImageMoniker
{
Guid = imageId.Guid,
Id = imageId.Id
};
}
}
}
return default;
}
}
// no shortcut support
string ISuggestedAction.InputGestureText => null;
#endregion
#region IEquatable<ISuggestedAction>
public bool Equals(ISuggestedAction other)
=> Equals(other as SuggestedAction);
public override bool Equals(object obj)
=> Equals(obj as SuggestedAction);
internal bool Equals(SuggestedAction otherSuggestedAction)
{
if (otherSuggestedAction == null)
{
return false;
}
if (this == otherSuggestedAction)
{
return true;
}
if (Provider != otherSuggestedAction.Provider)
{
return false;
}
var otherCodeAction = otherSuggestedAction.CodeAction;
if (CodeAction.EquivalenceKey == null || otherCodeAction.EquivalenceKey == null)
{
return false;
}
return CodeAction.EquivalenceKey == otherCodeAction.EquivalenceKey;
}
public override int GetHashCode()
{
if (CodeAction.EquivalenceKey == null)
{
return base.GetHashCode();
}
return Hash.Combine(Provider.GetHashCode(), CodeAction.EquivalenceKey.GetHashCode());
}
#endregion
internal TestAccessor GetTestAccessor()
=> new TestAccessor(this);
internal readonly struct TestAccessor
{
private readonly SuggestedAction _suggestedAction;
public TestAccessor(SuggestedAction suggestedAction)
=> _suggestedAction = suggestedAction;
public ref bool IsApplied => ref _suggestedAction._isApplied;
}
}
}
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/Implementation/CodeActions/CodeActionEditHandlerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeActions
{
[Export(typeof(ICodeActionEditHandlerService))]
internal class CodeActionEditHandlerService : ForegroundThreadAffinitizedObject, ICodeActionEditHandlerService
{
private readonly IPreviewFactoryService _previewService;
private readonly IInlineRenameService _renameService;
private readonly ITextBufferAssociatedViewService _associatedViewService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CodeActionEditHandlerService(
IThreadingContext threadingContext,
IPreviewFactoryService previewService,
IInlineRenameService renameService,
ITextBufferAssociatedViewService associatedViewService)
: base(threadingContext)
{
_previewService = previewService;
_renameService = renameService;
_associatedViewService = associatedViewService;
}
public ITextBufferAssociatedViewService AssociatedViewService => _associatedViewService;
public SolutionPreviewResult GetPreviews(
Workspace workspace, ImmutableArray<CodeActionOperation> operations, CancellationToken cancellationToken)
{
if (operations.IsDefaultOrEmpty)
{
return null;
}
SolutionPreviewResult currentResult = null;
foreach (var op in operations)
{
cancellationToken.ThrowIfCancellationRequested();
if (op is ApplyChangesOperation applyChanges)
{
var oldSolution = workspace.CurrentSolution;
var newSolution = applyChanges.ChangedSolution.WithMergedLinkedFileChangesAsync(oldSolution, cancellationToken: cancellationToken).WaitAndGetResult(cancellationToken);
var preview = _previewService.GetSolutionPreviews(
oldSolution, newSolution, cancellationToken);
if (preview != null && !preview.IsEmpty)
{
currentResult = SolutionPreviewResult.Merge(currentResult, preview);
continue;
}
}
if (op is PreviewOperation previewOp)
{
currentResult = SolutionPreviewResult.Merge(currentResult,
new SolutionPreviewResult(ThreadingContext, new SolutionPreviewItem(
projectId: null, documentId: null,
lazyPreview: c => previewOp.GetPreviewAsync(c))));
continue;
}
var title = op.Title;
if (title != null)
{
currentResult = SolutionPreviewResult.Merge(currentResult,
new SolutionPreviewResult(ThreadingContext, new SolutionPreviewItem(
projectId: null, documentId: null, text: title)));
continue;
}
}
return currentResult;
}
public bool Apply(
Workspace workspace, Document fromDocument,
ImmutableArray<CodeActionOperation> operations,
string title, IProgressTracker progressTracker,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (operations.IsDefaultOrEmpty)
{
return _renameService.ActiveSession is null;
}
if (_renameService.ActiveSession != null)
{
workspace.Services.GetService<INotificationService>()?.SendNotification(
EditorFeaturesResources.Cannot_apply_operation_while_a_rename_session_is_active,
severity: NotificationSeverity.Error);
return false;
}
#if DEBUG && false
var documentErrorLookup = new HashSet<DocumentId>();
foreach (var project in workspace.CurrentSolution.Projects)
{
foreach (var document in project.Documents)
{
if (!document.HasAnyErrorsAsync(cancellationToken).WaitAndGetResult(cancellationToken))
{
documentErrorLookup.Add(document.Id);
}
}
}
#endif
var oldSolution = workspace.CurrentSolution;
var applied = false;
// Determine if we're making a simple text edit to a single file or not.
// If we're not, then we need to make a linked global undo to wrap the
// application of these operations. This way we should be able to undo
// them all with one user action.
//
// The reason we don't always create a global undo is that a global undo
// forces all files to save. And that's rather a heavyweight and
// unexpected experience for users (for the common case where a single
// file got edited).
var singleChangedDocument = TryGetSingleChangedText(oldSolution, operations);
if (singleChangedDocument != null)
{
var text = singleChangedDocument.GetTextSynchronously(cancellationToken);
using (workspace.Services.GetService<ISourceTextUndoService>().RegisterUndoTransaction(text, title))
{
try
{
applied = operations.Single().TryApply(workspace, progressTracker, cancellationToken);
}
catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
else
{
// More than just a single document changed. Make a global undo to run
// all the changes under.
using var transaction = workspace.OpenGlobalUndoTransaction(title);
// link current file in the global undo transaction
// Do this before processing operations, since that can change
// documentIds.
if (fromDocument != null)
{
transaction.AddDocument(fromDocument.Id);
}
try
{
applied = ProcessOperations(
workspace, operations, progressTracker,
cancellationToken);
}
catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
transaction.Commit();
}
var updatedSolution = operations.OfType<ApplyChangesOperation>().FirstOrDefault()?.ChangedSolution ?? oldSolution;
TryNavigateToLocationOrStartRenameSession(workspace, oldSolution, updatedSolution, cancellationToken);
return applied;
}
private static TextDocument TryGetSingleChangedText(
Solution oldSolution, ImmutableArray<CodeActionOperation> operationsList)
{
Debug.Assert(operationsList.Length > 0);
if (operationsList.Length > 1)
{
return null;
}
if (!(operationsList.Single() is ApplyChangesOperation applyOperation))
{
return null;
}
var newSolution = applyOperation.ChangedSolution;
var changes = newSolution.GetChanges(oldSolution);
if (changes.GetAddedProjects().Any() ||
changes.GetRemovedProjects().Any())
{
return null;
}
var projectChanges = changes.GetProjectChanges().ToImmutableArray();
if (projectChanges.Length != 1)
{
return null;
}
var projectChange = projectChanges.Single();
if (projectChange.GetAddedAdditionalDocuments().Any() ||
projectChange.GetAddedAnalyzerReferences().Any() ||
projectChange.GetAddedDocuments().Any() ||
projectChange.GetAddedAnalyzerConfigDocuments().Any() ||
projectChange.GetAddedMetadataReferences().Any() ||
projectChange.GetAddedProjectReferences().Any() ||
projectChange.GetRemovedAdditionalDocuments().Any() ||
projectChange.GetRemovedAnalyzerReferences().Any() ||
projectChange.GetRemovedDocuments().Any() ||
projectChange.GetRemovedAnalyzerConfigDocuments().Any() ||
projectChange.GetRemovedMetadataReferences().Any() ||
projectChange.GetRemovedProjectReferences().Any())
{
return null;
}
var changedAdditionalDocuments = projectChange.GetChangedAdditionalDocuments().ToImmutableArray();
var changedDocuments = projectChange.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true).ToImmutableArray();
var changedAnalyzerConfigDocuments = projectChange.GetChangedAnalyzerConfigDocuments().ToImmutableArray();
if (changedAdditionalDocuments.Length + changedDocuments.Length + changedAnalyzerConfigDocuments.Length != 1)
{
return null;
}
if (changedDocuments.Any(id => newSolution.GetDocument(id).HasInfoChanged(oldSolution.GetDocument(id))) ||
changedAdditionalDocuments.Any(id => newSolution.GetAdditionalDocument(id).HasInfoChanged(oldSolution.GetAdditionalDocument(id))) ||
changedAnalyzerConfigDocuments.Any(id => newSolution.GetAnalyzerConfigDocument(id).HasInfoChanged(oldSolution.GetAnalyzerConfigDocument(id))))
{
return null;
}
if (changedDocuments.Length == 1)
{
return oldSolution.GetDocument(changedDocuments[0]);
}
else if (changedAdditionalDocuments.Length == 1)
{
return oldSolution.GetAdditionalDocument(changedAdditionalDocuments[0]);
}
else
{
return oldSolution.GetAnalyzerConfigDocument(changedAnalyzerConfigDocuments[0]);
}
}
/// <returns><see langword="true"/> if all expected <paramref name="operations"/> are applied successfully;
/// otherwise, <see langword="false"/>.</returns>
private static bool ProcessOperations(
Workspace workspace, ImmutableArray<CodeActionOperation> operations,
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
var applied = true;
var seenApplyChanges = false;
foreach (var operation in operations)
{
if (operation is ApplyChangesOperation)
{
// there must be only one ApplyChangesOperation, we will ignore all other ones.
if (seenApplyChanges)
{
continue;
}
seenApplyChanges = true;
}
applied &= operation.TryApply(workspace, progressTracker, cancellationToken);
}
return applied;
}
private void TryNavigateToLocationOrStartRenameSession(Workspace workspace, Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
{
var changedDocuments = newSolution.GetChangedDocuments(oldSolution);
foreach (var documentId in changedDocuments)
{
var document = newSolution.GetDocument(documentId);
if (!document.SupportsSyntaxTree)
{
continue;
}
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var navigationTokenOpt = root.GetAnnotatedTokens(NavigationAnnotation.Kind)
.FirstOrNull();
if (navigationTokenOpt.HasValue)
{
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
navigationService.TryNavigateToPosition(workspace, documentId, navigationTokenOpt.Value.SpanStart, cancellationToken);
return;
}
var renameTokenOpt = root.GetAnnotatedTokens(RenameAnnotation.Kind)
.FirstOrNull();
if (renameTokenOpt.HasValue)
{
// It's possible that the workspace's current solution is not the same as
// newSolution. This can happen if the workspace host performs other edits
// during ApplyChanges, such as in the Venus scenario where indentation and
// formatting can happen. To work around this, we create a SyntaxPath to the
// rename token in the newSolution and resolve it to the current solution.
var pathToRenameToken = new SyntaxPath(renameTokenOpt.Value);
var latestDocument = workspace.CurrentSolution.GetDocument(documentId);
var latestRoot = latestDocument.GetSyntaxRootSynchronously(cancellationToken);
if (pathToRenameToken.TryResolve(latestRoot, out var resolvedRenameToken) &&
resolvedRenameToken.IsToken)
{
var editorWorkspace = workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
if (navigationService.TryNavigateToSpan(editorWorkspace, documentId, resolvedRenameToken.Span, cancellationToken))
{
var openDocument = workspace.CurrentSolution.GetDocument(documentId);
var openRoot = openDocument.GetSyntaxRootSynchronously(cancellationToken);
// NOTE: We need to resolve the syntax path again in case VB line commit kicked in
// due to the navigation.
// TODO(DustinCa): We still have a potential problem here with VB line commit,
// because it can insert tokens and all sorts of other business, which could
// wind up with us not being able to resolve the token.
if (pathToRenameToken.TryResolve(openRoot, out resolvedRenameToken) &&
resolvedRenameToken.IsToken)
{
var snapshot = openDocument.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
_renameService.StartInlineSession(openDocument, resolvedRenameToken.AsToken().Span, cancellationToken);
}
}
}
}
return;
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Editor.Undo;
using Microsoft.CodeAnalysis.ErrorReporting;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Notification;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Implementation.CodeActions
{
[Export(typeof(ICodeActionEditHandlerService))]
internal class CodeActionEditHandlerService : ForegroundThreadAffinitizedObject, ICodeActionEditHandlerService
{
private readonly IPreviewFactoryService _previewService;
private readonly IInlineRenameService _renameService;
private readonly ITextBufferAssociatedViewService _associatedViewService;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CodeActionEditHandlerService(
IThreadingContext threadingContext,
IPreviewFactoryService previewService,
IInlineRenameService renameService,
ITextBufferAssociatedViewService associatedViewService)
: base(threadingContext)
{
_previewService = previewService;
_renameService = renameService;
_associatedViewService = associatedViewService;
}
public ITextBufferAssociatedViewService AssociatedViewService => _associatedViewService;
public async Task<SolutionPreviewResult> GetPreviewsAsync(
Workspace workspace, ImmutableArray<CodeActionOperation> operations, CancellationToken cancellationToken)
{
if (operations.IsDefaultOrEmpty)
return null;
SolutionPreviewResult currentResult = null;
foreach (var op in operations)
{
cancellationToken.ThrowIfCancellationRequested();
if (op is ApplyChangesOperation applyChanges)
{
var oldSolution = workspace.CurrentSolution;
var newSolution = await applyChanges.ChangedSolution.WithMergedLinkedFileChangesAsync(
oldSolution, cancellationToken: cancellationToken).ConfigureAwait(false);
var preview = _previewService.GetSolutionPreviews(
oldSolution, newSolution, cancellationToken);
if (preview != null && !preview.IsEmpty)
{
currentResult = SolutionPreviewResult.Merge(currentResult, preview);
continue;
}
}
if (op is PreviewOperation previewOp)
{
currentResult = SolutionPreviewResult.Merge(currentResult,
new SolutionPreviewResult(ThreadingContext, new SolutionPreviewItem(
projectId: null, documentId: null,
lazyPreview: c => previewOp.GetPreviewAsync(c))));
continue;
}
var title = op.Title;
if (title != null)
{
currentResult = SolutionPreviewResult.Merge(currentResult,
new SolutionPreviewResult(ThreadingContext, new SolutionPreviewItem(
projectId: null, documentId: null, text: title)));
continue;
}
}
return currentResult;
}
public bool Apply(
Workspace workspace, Document fromDocument,
ImmutableArray<CodeActionOperation> operations,
string title, IProgressTracker progressTracker,
CancellationToken cancellationToken)
{
this.AssertIsForeground();
if (operations.IsDefaultOrEmpty)
{
return _renameService.ActiveSession is null;
}
if (_renameService.ActiveSession != null)
{
workspace.Services.GetService<INotificationService>()?.SendNotification(
EditorFeaturesResources.Cannot_apply_operation_while_a_rename_session_is_active,
severity: NotificationSeverity.Error);
return false;
}
#if DEBUG && false
var documentErrorLookup = new HashSet<DocumentId>();
foreach (var project in workspace.CurrentSolution.Projects)
{
foreach (var document in project.Documents)
{
if (!document.HasAnyErrorsAsync(cancellationToken).WaitAndGetResult(cancellationToken))
{
documentErrorLookup.Add(document.Id);
}
}
}
#endif
var oldSolution = workspace.CurrentSolution;
var applied = false;
// Determine if we're making a simple text edit to a single file or not.
// If we're not, then we need to make a linked global undo to wrap the
// application of these operations. This way we should be able to undo
// them all with one user action.
//
// The reason we don't always create a global undo is that a global undo
// forces all files to save. And that's rather a heavyweight and
// unexpected experience for users (for the common case where a single
// file got edited).
var singleChangedDocument = TryGetSingleChangedText(oldSolution, operations);
if (singleChangedDocument != null)
{
var text = singleChangedDocument.GetTextSynchronously(cancellationToken);
using (workspace.Services.GetService<ISourceTextUndoService>().RegisterUndoTransaction(text, title))
{
try
{
applied = operations.Single().TryApply(workspace, progressTracker, cancellationToken);
}
catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
}
}
else
{
// More than just a single document changed. Make a global undo to run
// all the changes under.
using var transaction = workspace.OpenGlobalUndoTransaction(title);
// link current file in the global undo transaction
// Do this before processing operations, since that can change
// documentIds.
if (fromDocument != null)
{
transaction.AddDocument(fromDocument.Id);
}
try
{
applied = ProcessOperations(
workspace, operations, progressTracker,
cancellationToken);
}
catch (Exception ex) when (FatalError.ReportAndPropagateUnlessCanceled(ex, cancellationToken))
{
throw ExceptionUtilities.Unreachable;
}
transaction.Commit();
}
var updatedSolution = operations.OfType<ApplyChangesOperation>().FirstOrDefault()?.ChangedSolution ?? oldSolution;
TryNavigateToLocationOrStartRenameSession(workspace, oldSolution, updatedSolution, cancellationToken);
return applied;
}
private static TextDocument TryGetSingleChangedText(
Solution oldSolution, ImmutableArray<CodeActionOperation> operationsList)
{
Debug.Assert(operationsList.Length > 0);
if (operationsList.Length > 1)
{
return null;
}
if (!(operationsList.Single() is ApplyChangesOperation applyOperation))
{
return null;
}
var newSolution = applyOperation.ChangedSolution;
var changes = newSolution.GetChanges(oldSolution);
if (changes.GetAddedProjects().Any() ||
changes.GetRemovedProjects().Any())
{
return null;
}
var projectChanges = changes.GetProjectChanges().ToImmutableArray();
if (projectChanges.Length != 1)
{
return null;
}
var projectChange = projectChanges.Single();
if (projectChange.GetAddedAdditionalDocuments().Any() ||
projectChange.GetAddedAnalyzerReferences().Any() ||
projectChange.GetAddedDocuments().Any() ||
projectChange.GetAddedAnalyzerConfigDocuments().Any() ||
projectChange.GetAddedMetadataReferences().Any() ||
projectChange.GetAddedProjectReferences().Any() ||
projectChange.GetRemovedAdditionalDocuments().Any() ||
projectChange.GetRemovedAnalyzerReferences().Any() ||
projectChange.GetRemovedDocuments().Any() ||
projectChange.GetRemovedAnalyzerConfigDocuments().Any() ||
projectChange.GetRemovedMetadataReferences().Any() ||
projectChange.GetRemovedProjectReferences().Any())
{
return null;
}
var changedAdditionalDocuments = projectChange.GetChangedAdditionalDocuments().ToImmutableArray();
var changedDocuments = projectChange.GetChangedDocuments(onlyGetDocumentsWithTextChanges: true).ToImmutableArray();
var changedAnalyzerConfigDocuments = projectChange.GetChangedAnalyzerConfigDocuments().ToImmutableArray();
if (changedAdditionalDocuments.Length + changedDocuments.Length + changedAnalyzerConfigDocuments.Length != 1)
{
return null;
}
if (changedDocuments.Any(id => newSolution.GetDocument(id).HasInfoChanged(oldSolution.GetDocument(id))) ||
changedAdditionalDocuments.Any(id => newSolution.GetAdditionalDocument(id).HasInfoChanged(oldSolution.GetAdditionalDocument(id))) ||
changedAnalyzerConfigDocuments.Any(id => newSolution.GetAnalyzerConfigDocument(id).HasInfoChanged(oldSolution.GetAnalyzerConfigDocument(id))))
{
return null;
}
if (changedDocuments.Length == 1)
{
return oldSolution.GetDocument(changedDocuments[0]);
}
else if (changedAdditionalDocuments.Length == 1)
{
return oldSolution.GetAdditionalDocument(changedAdditionalDocuments[0]);
}
else
{
return oldSolution.GetAnalyzerConfigDocument(changedAnalyzerConfigDocuments[0]);
}
}
/// <returns><see langword="true"/> if all expected <paramref name="operations"/> are applied successfully;
/// otherwise, <see langword="false"/>.</returns>
private static bool ProcessOperations(
Workspace workspace, ImmutableArray<CodeActionOperation> operations,
IProgressTracker progressTracker, CancellationToken cancellationToken)
{
var applied = true;
var seenApplyChanges = false;
foreach (var operation in operations)
{
if (operation is ApplyChangesOperation)
{
// there must be only one ApplyChangesOperation, we will ignore all other ones.
if (seenApplyChanges)
{
continue;
}
seenApplyChanges = true;
}
applied &= operation.TryApply(workspace, progressTracker, cancellationToken);
}
return applied;
}
private void TryNavigateToLocationOrStartRenameSession(Workspace workspace, Solution oldSolution, Solution newSolution, CancellationToken cancellationToken)
{
var changedDocuments = newSolution.GetChangedDocuments(oldSolution);
foreach (var documentId in changedDocuments)
{
var document = newSolution.GetDocument(documentId);
if (!document.SupportsSyntaxTree)
{
continue;
}
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var navigationTokenOpt = root.GetAnnotatedTokens(NavigationAnnotation.Kind)
.FirstOrNull();
if (navigationTokenOpt.HasValue)
{
var navigationService = workspace.Services.GetService<IDocumentNavigationService>();
navigationService.TryNavigateToPosition(workspace, documentId, navigationTokenOpt.Value.SpanStart, cancellationToken);
return;
}
var renameTokenOpt = root.GetAnnotatedTokens(RenameAnnotation.Kind)
.FirstOrNull();
if (renameTokenOpt.HasValue)
{
// It's possible that the workspace's current solution is not the same as
// newSolution. This can happen if the workspace host performs other edits
// during ApplyChanges, such as in the Venus scenario where indentation and
// formatting can happen. To work around this, we create a SyntaxPath to the
// rename token in the newSolution and resolve it to the current solution.
var pathToRenameToken = new SyntaxPath(renameTokenOpt.Value);
var latestDocument = workspace.CurrentSolution.GetDocument(documentId);
var latestRoot = latestDocument.GetSyntaxRootSynchronously(cancellationToken);
if (pathToRenameToken.TryResolve(latestRoot, out var resolvedRenameToken) &&
resolvedRenameToken.IsToken)
{
var editorWorkspace = workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
if (navigationService.TryNavigateToSpan(editorWorkspace, documentId, resolvedRenameToken.Span, cancellationToken))
{
var openDocument = workspace.CurrentSolution.GetDocument(documentId);
var openRoot = openDocument.GetSyntaxRootSynchronously(cancellationToken);
// NOTE: We need to resolve the syntax path again in case VB line commit kicked in
// due to the navigation.
// TODO(DustinCa): We still have a potential problem here with VB line commit,
// because it can insert tokens and all sorts of other business, which could
// wind up with us not being able to resolve the token.
if (pathToRenameToken.TryResolve(openRoot, out resolvedRenameToken) &&
resolvedRenameToken.IsToken)
{
var snapshot = openDocument.GetTextSynchronously(cancellationToken).FindCorrespondingEditorTextSnapshot();
if (snapshot != null)
{
_renameService.StartInlineSession(openDocument, resolvedRenameToken.AsToken().Span, cancellationToken);
}
}
}
}
return;
}
}
}
}
}
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/Implementation/CodeRefactorings/ICodeActionEditHandlerService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
internal interface ICodeActionEditHandlerService
{
ITextBufferAssociatedViewService AssociatedViewService { get; }
SolutionPreviewResult GetPreviews(
Workspace workspace, ImmutableArray<CodeActionOperation> operations, CancellationToken cancellationToken);
bool Apply(
Workspace workspace, Document fromDocument,
ImmutableArray<CodeActionOperation> operations,
string title, IProgressTracker progressTracker,
CancellationToken cancellationToken);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Shared.Utilities;
namespace Microsoft.CodeAnalysis.Editor
{
internal interface ICodeActionEditHandlerService
{
ITextBufferAssociatedViewService AssociatedViewService { get; }
Task<SolutionPreviewResult> GetPreviewsAsync(
Workspace workspace, ImmutableArray<CodeActionOperation> operations, CancellationToken cancellationToken);
bool Apply(
Workspace workspace, Document fromDocument,
ImmutableArray<CodeActionOperation> operations,
string title, IProgressTracker progressTracker,
CancellationToken cancellationToken);
}
}
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionOrUserDiagnosticTest_TestAddDocument.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract partial class AbstractCodeActionOrUserDiagnosticTest
{
protected async Task TestAddDocumentInRegularAndScriptAsync(
string initialMarkup, string expectedMarkup,
ImmutableArray<string> expectedContainers,
string expectedDocumentName,
TestParameters parameters = default)
{
await TestAddDocument(
initialMarkup, expectedMarkup,
expectedContainers, expectedDocumentName,
WithRegularOptions(parameters));
// VB script is not supported:
if (GetLanguage() == LanguageNames.CSharp)
{
await TestAddDocument(
initialMarkup, expectedMarkup,
expectedContainers, expectedDocumentName,
WithScriptOptions(parameters));
}
}
protected async Task<Tuple<Solution, Solution>> TestAddDocumentAsync(
TestParameters parameters,
TestWorkspace workspace,
string expectedMarkup,
string expectedDocumentName,
ImmutableArray<string> expectedContainers)
{
var (_, action) = await GetCodeActionsAsync(workspace, parameters);
return await TestAddDocument(
workspace, expectedMarkup, expectedContainers,
expectedDocumentName, action);
}
protected async Task TestAddDocument(
string initialMarkup,
string expectedMarkup,
ImmutableArray<string> expectedContainers,
string expectedDocumentName,
TestParameters parameters = default)
{
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters))
{
var (_, action) = await GetCodeActionsAsync(workspace, parameters);
await TestAddDocument(
workspace, expectedMarkup, expectedContainers,
expectedDocumentName, action);
}
}
private async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expectedMarkup,
ImmutableArray<string> expectedFolders,
string expectedDocumentName,
CodeAction action)
{
var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
return await TestAddDocument(
workspace,
expectedMarkup,
operations,
hasProjectChange: false,
modifiedProjectId: null,
expectedFolders: expectedFolders,
expectedDocumentName: expectedDocumentName);
}
protected static async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expected,
ImmutableArray<CodeActionOperation> operations,
bool hasProjectChange,
ProjectId modifiedProjectId,
ImmutableArray<string> expectedFolders,
string expectedDocumentName)
{
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1;
var newSolution = appliedChanges.Item2;
Document addedDocument = null;
if (!hasProjectChange)
{
addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
}
else
{
Assert.NotNull(modifiedProjectId);
addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
}
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
var actual = (await addedDocument.GetTextAsync()).ToString();
Assert.Equal(expected, actual);
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
if (!hasProjectChange)
{
// If there is just one document change then we expect the preview to be a WpfTextView
var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0];
using (var diffView = content as DifferenceViewerPreview)
{
Assert.NotNull(diffView.Viewer);
}
}
else
{
// If there are more changes than just the document we need to browse all the changes and get the document change
var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None);
var hasPreview = false;
var previews = await contents.GetPreviewsAsync();
if (previews != null)
{
foreach (var preview in previews)
{
if (preview != null)
{
var diffView = preview as DifferenceViewerPreview;
if (diffView?.Viewer != null)
{
hasPreview = true;
diffView.Dispose();
break;
}
}
}
}
Assert.True(hasPreview);
}
return Tuple.Create(oldSolution, newSolution);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.UnitTests;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract partial class AbstractCodeActionOrUserDiagnosticTest
{
protected async Task TestAddDocumentInRegularAndScriptAsync(
string initialMarkup, string expectedMarkup,
ImmutableArray<string> expectedContainers,
string expectedDocumentName,
TestParameters parameters = default)
{
await TestAddDocument(
initialMarkup, expectedMarkup,
expectedContainers, expectedDocumentName,
WithRegularOptions(parameters));
// VB script is not supported:
if (GetLanguage() == LanguageNames.CSharp)
{
await TestAddDocument(
initialMarkup, expectedMarkup,
expectedContainers, expectedDocumentName,
WithScriptOptions(parameters));
}
}
protected async Task<Tuple<Solution, Solution>> TestAddDocumentAsync(
TestParameters parameters,
TestWorkspace workspace,
string expectedMarkup,
string expectedDocumentName,
ImmutableArray<string> expectedContainers)
{
var (_, action) = await GetCodeActionsAsync(workspace, parameters);
return await TestAddDocument(
workspace, expectedMarkup, expectedContainers,
expectedDocumentName, action);
}
protected async Task TestAddDocument(
string initialMarkup,
string expectedMarkup,
ImmutableArray<string> expectedContainers,
string expectedDocumentName,
TestParameters parameters = default)
{
using (var workspace = CreateWorkspaceFromOptions(initialMarkup, parameters))
{
var (_, action) = await GetCodeActionsAsync(workspace, parameters);
await TestAddDocument(
workspace, expectedMarkup, expectedContainers,
expectedDocumentName, action);
}
}
private async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expectedMarkup,
ImmutableArray<string> expectedFolders,
string expectedDocumentName,
CodeAction action)
{
var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
return await TestAddDocument(
workspace,
expectedMarkup,
operations,
hasProjectChange: false,
modifiedProjectId: null,
expectedFolders: expectedFolders,
expectedDocumentName: expectedDocumentName);
}
protected static async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expected,
ImmutableArray<CodeActionOperation> operations,
bool hasProjectChange,
ProjectId modifiedProjectId,
ImmutableArray<string> expectedFolders,
string expectedDocumentName)
{
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1;
var newSolution = appliedChanges.Item2;
Document addedDocument = null;
if (!hasProjectChange)
{
addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
}
else
{
Assert.NotNull(modifiedProjectId);
addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
}
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
var actual = (await addedDocument.GetTextAsync()).ToString();
Assert.Equal(expected, actual);
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
if (!hasProjectChange)
{
// If there is just one document change then we expect the preview to be a WpfTextView
var previews = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None);
var content = (await previews.GetPreviewsAsync())[0];
using (var diffView = content as DifferenceViewerPreview)
{
Assert.NotNull(diffView.Viewer);
}
}
else
{
// If there are more changes than just the document we need to browse all the changes and get the document change
var contents = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None);
var hasPreview = false;
var previews = await contents.GetPreviewsAsync();
if (previews != null)
{
foreach (var preview in previews)
{
if (preview != null)
{
var diffView = preview as DifferenceViewerPreview;
if (diffView?.Viewer != null)
{
hasPreview = true;
diffView.Dispose();
break;
}
}
}
}
Assert.True(hasPreview);
}
return Tuple.Create(oldSolution, newSolution);
}
}
}
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/DiagnosticsTestUtilities/CodeActions/AbstractCodeActionTest.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest
{
protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider(
Workspace workspace, TestParameters parameters);
protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var refactoring = await GetCodeRefactoringAsync(workspace, parameters);
var actions = refactoring == null
? ImmutableArray<CodeAction>.Empty
: refactoring.CodeActions.Select(n => n.action).AsImmutable();
actions = MassageActions(actions);
return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]);
}
protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters)
=> SpecializedTasks.EmptyImmutableArray<Diagnostic>();
internal async Task<CodeRefactoring> GetCodeRefactoringAsync(
TestWorkspace workspace, TestParameters parameters)
{
return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault();
}
private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var provider = CreateCodeRefactoringProvider(workspace, parameters);
return SpecializedCollections.SingletonEnumerable(
await GetCodeRefactoringAsync(provider, workspace));
}
private static async Task<CodeRefactoring> GetCodeRefactoringAsync(
CodeRefactoringProvider provider,
TestWorkspace workspace)
{
var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1);
Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation");
var span = documentsWithSelections.Single().SelectedSpans.Single();
var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance();
var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id);
var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None);
await provider.ComputeRefactoringsAsync(context);
var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null;
actions.Free();
return result;
}
protected async Task TestActionOnLinkedFiles(
TestWorkspace workspace,
string expectedText,
CodeAction action,
string expectedPreviewContents = null)
{
var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
await VerifyPreviewContents(workspace, expectedPreviewContents, operations);
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None);
foreach (var document in workspace.Documents)
{
var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync();
var actualText = fixedRoot.ToFullString();
Assert.Equal(expectedText, actualText);
}
}
private static async Task VerifyPreviewContents(
TestWorkspace workspace, string expectedPreviewContents,
ImmutableArray<CodeActionOperation> operations)
{
if (expectedPreviewContents != null)
{
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var content = (await editHandler.GetPreviews(workspace, operations, CancellationToken.None).GetPreviewsAsync())[0];
var diffView = content as DifferenceViewerPreview;
Assert.NotNull(diffView.Viewer);
var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
diffView.Dispose();
Assert.Equal(expectedPreviewContents, previewContents);
}
}
protected static Document GetDocument(TestWorkspace workspace)
=> workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
internal static void EnableOptions(
ImmutableArray<PickMembersOption> options,
params string[] ids)
{
foreach (var id in ids)
{
EnableOption(options, id);
}
}
internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id)
{
var option = options.FirstOrDefault(o => o.Id == id);
if (option != null)
{
option.Value = true;
}
}
internal Task TestWithPickMembersDialogAsync(
string initialMarkup,
string expectedMarkup,
string[] chosenSymbols,
Action<ImmutableArray<PickMembersOption>> optionsCallback = null,
int index = 0,
TestParameters parameters = default)
{
var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback);
return TestInRegularAndScript1Async(
initialMarkup, expectedMarkup,
index,
parameters.WithFixProviderData(pickMembersService));
}
}
[ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable]
internal class TestPickMembersService : IPickMembersService
{
public ImmutableArray<string> MemberNames;
public Action<ImmutableArray<PickMembersOption>> OptionsCallback;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestPickMembersService()
{
}
#pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public TestPickMembersService(
ImmutableArray<string> memberNames,
Action<ImmutableArray<PickMembersOption>> optionsCallback)
{
MemberNames = memberNames;
OptionsCallback = optionsCallback;
}
#pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public PickMembersResult PickMembers(
string title,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
OptionsCallback?.Invoke(options);
return new PickMembersResult(
MemberNames.IsDefault
? members
: MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)),
options,
selectAll);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editor.Implementation.Preview;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.PickMembers;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions
{
public abstract partial class AbstractCodeActionTest : AbstractCodeActionOrUserDiagnosticTest
{
protected abstract CodeRefactoringProvider CreateCodeRefactoringProvider(
Workspace workspace, TestParameters parameters);
protected override async Task<(ImmutableArray<CodeAction>, CodeAction actionToInvoke)> GetCodeActionsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var refactoring = await GetCodeRefactoringAsync(workspace, parameters);
var actions = refactoring == null
? ImmutableArray<CodeAction>.Empty
: refactoring.CodeActions.Select(n => n.action).AsImmutable();
actions = MassageActions(actions);
return (actions, actions.IsDefaultOrEmpty ? null : actions[parameters.index]);
}
protected override Task<ImmutableArray<Diagnostic>> GetDiagnosticsWorkerAsync(TestWorkspace workspace, TestParameters parameters)
=> SpecializedTasks.EmptyImmutableArray<Diagnostic>();
internal async Task<CodeRefactoring> GetCodeRefactoringAsync(
TestWorkspace workspace, TestParameters parameters)
{
return (await GetCodeRefactoringsAsync(workspace, parameters)).FirstOrDefault();
}
private async Task<IEnumerable<CodeRefactoring>> GetCodeRefactoringsAsync(
TestWorkspace workspace, TestParameters parameters)
{
var provider = CreateCodeRefactoringProvider(workspace, parameters);
return SpecializedCollections.SingletonEnumerable(
await GetCodeRefactoringAsync(provider, workspace));
}
private static async Task<CodeRefactoring> GetCodeRefactoringAsync(
CodeRefactoringProvider provider,
TestWorkspace workspace)
{
var documentsWithSelections = workspace.Documents.Where(d => !d.IsLinkFile && d.SelectedSpans.Count == 1);
Debug.Assert(documentsWithSelections.Count() == 1, "One document must have a single span annotation");
var span = documentsWithSelections.Single().SelectedSpans.Single();
var actions = ArrayBuilder<(CodeAction, TextSpan?)>.GetInstance();
var document = workspace.CurrentSolution.GetDocument(documentsWithSelections.Single().Id);
var context = new CodeRefactoringContext(document, span, (a, t) => actions.Add((a, t)), isBlocking: false, CancellationToken.None);
await provider.ComputeRefactoringsAsync(context);
var result = actions.Count > 0 ? new CodeRefactoring(provider, actions.ToImmutable()) : null;
actions.Free();
return result;
}
protected async Task TestActionOnLinkedFiles(
TestWorkspace workspace,
string expectedText,
CodeAction action,
string expectedPreviewContents = null)
{
var operations = await VerifyActionAndGetOperationsAsync(workspace, action, default);
await VerifyPreviewContents(workspace, expectedPreviewContents, operations);
var applyChangesOperation = operations.OfType<ApplyChangesOperation>().First();
applyChangesOperation.TryApply(workspace, new ProgressTracker(), CancellationToken.None);
foreach (var document in workspace.Documents)
{
var fixedRoot = await workspace.CurrentSolution.GetDocument(document.Id).GetSyntaxRootAsync();
var actualText = fixedRoot.ToFullString();
Assert.Equal(expectedText, actualText);
}
}
private static async Task VerifyPreviewContents(
TestWorkspace workspace, string expectedPreviewContents,
ImmutableArray<CodeActionOperation> operations)
{
if (expectedPreviewContents != null)
{
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
var previews = await editHandler.GetPreviewsAsync(workspace, operations, CancellationToken.None);
var content = (await previews.GetPreviewsAsync())[0];
var diffView = content as DifferenceViewerPreview;
Assert.NotNull(diffView.Viewer);
var previewContents = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString();
diffView.Dispose();
Assert.Equal(expectedPreviewContents, previewContents);
}
}
protected static Document GetDocument(TestWorkspace workspace)
=> workspace.CurrentSolution.GetDocument(workspace.Documents.First().Id);
internal static void EnableOptions(
ImmutableArray<PickMembersOption> options,
params string[] ids)
{
foreach (var id in ids)
{
EnableOption(options, id);
}
}
internal static void EnableOption(ImmutableArray<PickMembersOption> options, string id)
{
var option = options.FirstOrDefault(o => o.Id == id);
if (option != null)
{
option.Value = true;
}
}
internal Task TestWithPickMembersDialogAsync(
string initialMarkup,
string expectedMarkup,
string[] chosenSymbols,
Action<ImmutableArray<PickMembersOption>> optionsCallback = null,
int index = 0,
TestParameters parameters = default)
{
var pickMembersService = new TestPickMembersService(chosenSymbols.AsImmutableOrNull(), optionsCallback);
return TestInRegularAndScript1Async(
initialMarkup, expectedMarkup,
index,
parameters.WithFixProviderData(pickMembersService));
}
}
[ExportWorkspaceService(typeof(IPickMembersService), ServiceLayer.Host), Shared, PartNotDiscoverable]
internal class TestPickMembersService : IPickMembersService
{
public ImmutableArray<string> MemberNames;
public Action<ImmutableArray<PickMembersOption>> OptionsCallback;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public TestPickMembersService()
{
}
#pragma warning disable RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public TestPickMembersService(
ImmutableArray<string> memberNames,
Action<ImmutableArray<PickMembersOption>> optionsCallback)
{
MemberNames = memberNames;
OptionsCallback = optionsCallback;
}
#pragma warning restore RS0034 // Exported parts should be marked with 'ImportingConstructorAttribute'
public PickMembersResult PickMembers(
string title,
ImmutableArray<ISymbol> members,
ImmutableArray<PickMembersOption> options,
bool selectAll)
{
OptionsCallback?.Invoke(options);
return new PickMembersResult(
MemberNames.IsDefault
? members
: MemberNames.SelectAsArray(n => members.Single(m => m.Name == n)),
options,
selectAll);
}
}
}
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/VisualBasicTest/CodeActions/Preview/PreviewTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.Implementation.Preview
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Public Class PreviewTests
Inherits AbstractVisualBasicCodeActionTest
Private Const s_addedDocumentName As String = "AddedDocument"
Private Const s_addedDocumentText As String = "Class C1 : End Class"
Private Shared s_removedMetadataReferenceDisplayName As String = ""
Private Const s_addedProjectName As String = "AddedProject"
Private Shared ReadOnly s_addedProjectId As ProjectId = ProjectId.CreateNewId()
Private Const s_changedDocumentText As String = "Class C : End Class"
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New MyCodeRefactoringProvider()
End Function
Private Class MyCodeRefactoringProvider : Inherits CodeRefactoringProvider
Public NotOverridable Overrides Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task
Dim codeAction = New MyCodeAction(context.Document)
context.RegisterRefactoring(codeAction, context.Span)
Return Task.CompletedTask
End Function
Private Class MyCodeAction : Inherits CodeAction
Private ReadOnly _oldDocument As Document
Public Sub New(oldDocument As Document)
Me._oldDocument = oldDocument
End Sub
Public Overrides ReadOnly Property Title As String
Get
Return "Title"
End Get
End Property
Protected Overrides Function GetChangedSolutionAsync(cancellationToken As CancellationToken) As Task(Of Solution)
Dim solution = _oldDocument.Project.Solution
' Add a document - This will result in IWpfTextView previews.
solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, s_addedDocumentName), s_addedDocumentName, s_addedDocumentText)
' Remove a reference - This will result in a string preview.
Dim removedReference = _oldDocument.Project.MetadataReferences.Last()
s_removedMetadataReferenceDisplayName = removedReference.Display
solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference)
' Add a project - This will result in a string preview.
solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), s_addedProjectName, s_addedProjectName, LanguageNames.CSharp))
' Change a document - This will result in IWpfTextView previews.
solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, VisualBasicSyntaxTree.ParseText(s_changedDocumentText).GetRoot())
Return Task.FromResult(solution)
End Function
End Class
End Class
Private Sub GetMainDocumentAndPreviews(parameters As TestParameters, workspace As TestWorkspace, ByRef document As Document, ByRef previews As SolutionPreviewResult)
document = GetDocument(workspace)
Dim provider = CreateCodeRefactoringProvider(workspace, parameters)
Dim span = document.GetSyntaxRootAsync().Result.Span
Dim refactorings = New List(Of CodeAction)()
Dim context = New CodeRefactoringContext(document, span, Sub(a) refactorings.Add(a), CancellationToken.None)
provider.ComputeRefactoringsAsync(context).Wait()
Dim action = refactorings.Single()
Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)()
previews = editHandler.GetPreviews(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None)
End Sub
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/14421")>
Public Async Function TestPickTheRightPreview_NoPreference() As Task
Dim parameters As New TestParameters()
Using workspace = CreateWorkspaceFromOptions("Class D : End Class", parameters)
Dim document As Document = Nothing
Dim previews As SolutionPreviewResult = Nothing
GetMainDocumentAndPreviews(parameters, workspace, document, previews)
' The changed document comes first.
Dim previewObjects = Await previews.GetPreviewsAsync()
Dim preview = previewObjects(0)
Assert.NotNull(preview)
Assert.True(TypeOf preview Is DifferenceViewerPreview)
Dim diffView = DirectCast(preview, DifferenceViewerPreview)
Dim text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString()
Assert.Equal(s_changedDocumentText, text)
diffView.Dispose()
' Then comes the removed metadata reference.
preview = previewObjects(1)
Assert.NotNull(preview)
Assert.True(TypeOf preview Is String)
text = DirectCast(preview, String)
Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal)
' And finally the added project.
preview = previewObjects(2)
Assert.NotNull(preview)
Assert.True(TypeOf preview Is String)
text = DirectCast(preview, String)
Assert.Contains(s_addedProjectName, text, StringComparison.Ordinal)
End Using
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Threading
Imports Microsoft.CodeAnalysis.CodeActions
Imports Microsoft.CodeAnalysis.CodeRefactorings
Imports Microsoft.CodeAnalysis.Editor.Implementation.Preview
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Text
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings
Public Class PreviewTests
Inherits AbstractVisualBasicCodeActionTest
Private Const s_addedDocumentName As String = "AddedDocument"
Private Const s_addedDocumentText As String = "Class C1 : End Class"
Private Shared s_removedMetadataReferenceDisplayName As String = ""
Private Const s_addedProjectName As String = "AddedProject"
Private Shared ReadOnly s_addedProjectId As ProjectId = ProjectId.CreateNewId()
Private Const s_changedDocumentText As String = "Class C : End Class"
Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider
Return New MyCodeRefactoringProvider()
End Function
Private Class MyCodeRefactoringProvider : Inherits CodeRefactoringProvider
Public NotOverridable Overrides Function ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task
Dim codeAction = New MyCodeAction(context.Document)
context.RegisterRefactoring(codeAction, context.Span)
Return Task.CompletedTask
End Function
Private Class MyCodeAction : Inherits CodeAction
Private ReadOnly _oldDocument As Document
Public Sub New(oldDocument As Document)
Me._oldDocument = oldDocument
End Sub
Public Overrides ReadOnly Property Title As String
Get
Return "Title"
End Get
End Property
Protected Overrides Function GetChangedSolutionAsync(cancellationToken As CancellationToken) As Task(Of Solution)
Dim solution = _oldDocument.Project.Solution
' Add a document - This will result in IWpfTextView previews.
solution = solution.AddDocument(DocumentId.CreateNewId(_oldDocument.Project.Id, s_addedDocumentName), s_addedDocumentName, s_addedDocumentText)
' Remove a reference - This will result in a string preview.
Dim removedReference = _oldDocument.Project.MetadataReferences.Last()
s_removedMetadataReferenceDisplayName = removedReference.Display
solution = solution.RemoveMetadataReference(_oldDocument.Project.Id, removedReference)
' Add a project - This will result in a string preview.
solution = solution.AddProject(ProjectInfo.Create(s_addedProjectId, VersionStamp.Create(), s_addedProjectName, s_addedProjectName, LanguageNames.CSharp))
' Change a document - This will result in IWpfTextView previews.
solution = solution.WithDocumentSyntaxRoot(_oldDocument.Id, VisualBasicSyntaxTree.ParseText(s_changedDocumentText).GetRoot())
Return Task.FromResult(solution)
End Function
End Class
End Class
Private Async Function GetMainDocumentAndPreviewsAsync(
parameters As TestParameters,
workspace As TestWorkspace) As Task(Of (document As Document, previews As SolutionPreviewResult))
Dim document = GetDocument(workspace)
Dim provider = CreateCodeRefactoringProvider(workspace, parameters)
Dim span = document.GetSyntaxRootAsync().Result.Span
Dim refactorings = New List(Of CodeAction)()
Dim context = New CodeRefactoringContext(document, span, Sub(a) refactorings.Add(a), CancellationToken.None)
provider.ComputeRefactoringsAsync(context).Wait()
Dim action = refactorings.Single()
Dim editHandler = workspace.ExportProvider.GetExportedValue(Of ICodeActionEditHandlerService)()
Dim previews = Await editHandler.GetPreviewsAsync(workspace, action.GetPreviewOperationsAsync(CancellationToken.None).Result, CancellationToken.None)
Return (document, previews)
End Function
<WpfFact(Skip:="https://github.com/dotnet/roslyn/issues/14421")>
Public Async Function TestPickTheRightPreview_NoPreference() As Task
Dim parameters As New TestParameters()
Using workspace = CreateWorkspaceFromOptions("Class D : End Class", parameters)
Dim tuple = Await GetMainDocumentAndPreviewsAsync(parameters, workspace)
Dim document = tuple.document
Dim previews = tuple.previews
' The changed document comes first.
Dim previewObjects = Await previews.GetPreviewsAsync()
Dim preview = previewObjects(0)
Assert.NotNull(preview)
Assert.True(TypeOf preview Is DifferenceViewerPreview)
Dim diffView = DirectCast(preview, DifferenceViewerPreview)
Dim text = diffView.Viewer.RightView.TextBuffer.AsTextContainer().CurrentText.ToString()
Assert.Equal(s_changedDocumentText, text)
diffView.Dispose()
' Then comes the removed metadata reference.
preview = previewObjects(1)
Assert.NotNull(preview)
Assert.True(TypeOf preview Is String)
text = DirectCast(preview, String)
Assert.Contains(s_removedMetadataReferenceDisplayName, text, StringComparison.Ordinal)
' And finally the added project.
preview = previewObjects(2)
Assert.NotNull(preview)
Assert.True(TypeOf preview Is String)
text = DirectCast(preview, String)
Assert.Contains(s_addedProjectName, text, StringComparison.Ordinal)
End Using
End Function
End Class
End Namespace
| 1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Workspaces/CoreTestUtilities/NoCompilationConstants.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.UnitTests
{
public class NoCompilationConstants
{
public const string LanguageName = "NoCompilation";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.CodeAnalysis.UnitTests
{
public class NoCompilationConstants
{
public const string LanguageName = "NoCompilation";
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/Core/Portable/GenerateType/AbstractGenerateTypeService.GenerateNamedType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
private partial class Editor
{
private async Task<INamedTypeSymbol> GenerateNamedTypeAsync()
{
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
DetermineAccessibility(),
DetermineModifiers(),
DetermineTypeKind(),
DetermineName(),
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: await DetermineMembersAsync().ConfigureAwait(false));
}
private async Task<INamedTypeSymbol> GenerateNamedTypeAsync(GenerateTypeOptionsResult options)
{
if (options.TypeKind == TypeKind.Delegate)
{
return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
DetermineReturnType(),
RefKind.None,
name: options.TypeName,
typeParameters: DetermineTypeParametersWithDelegateChecks(),
parameters: DetermineParameters());
}
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
options.TypeKind,
options.TypeName,
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: await DetermineMembersAsync(options).ConfigureAwait(false));
}
private ITypeSymbol DetermineReturnType()
{
if (_state.DelegateMethodSymbol == null ||
_state.DelegateMethodSymbol.ReturnType == null ||
_state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol)
{
// Since we cannot determine the return type, we are returning void
return _state.Compilation.GetSpecialType(SpecialType.System_Void);
}
else
{
return _state.DelegateMethodSymbol.ReturnType;
}
}
private ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWithDelegateChecks()
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.TypeParameters;
}
// If the delegate symbol cannot be determined then
return DetermineTypeParameters();
}
private ImmutableArray<IParameterSymbol> DetermineParameters()
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.Parameters;
}
return default;
}
private async Task<ImmutableArray<ISymbol>> DetermineMembersAsync(GenerateTypeOptionsResult options = null)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members);
await AddMembersAsync(members, options).ConfigureAwait(false);
if (_state.IsException)
AddExceptionConstructors(members);
return members.ToImmutable();
}
private async Task AddMembersAsync(ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null)
{
AddProperties(members);
if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out var argumentList))
{
return;
}
var parameterTypes = GetArgumentTypes(argumentList);
// Don't generate this constructor if it would conflict with a default exception
// constructor. Default exception constructors will be added automatically by our
// caller.
if (_state.IsException &&
_state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any(
c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes, SymbolEqualityComparer.Default)))
{
return;
}
// If there's an accessible base constructor that would accept these types, then
// just call into that instead of generating fields.
if (_state.BaseTypeOrInterfaceOpt != null)
{
if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface || argumentList.Count == 0)
{
// No need to add the default constructor if our base type is going to be 'object' or if we
// would be calling the empty constructor. We get that base constructor implicitly.
return;
}
// Synthesize some parameter symbols so we can see if these particular parameters could map to the
// parameters of any of the constructors we have in our base class. This will have the added
// benefit of allowing us to infer better types for complex type-less expressions (like lambdas).
var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
var refKinds = argumentList.SelectAsArray(a => syntaxFacts.GetRefKindOfArgument(a));
var parameters = parameterTypes.Zip(refKinds,
(t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray();
var expressions = GetArgumentExpressions(argumentList);
var delegatedConstructor = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.FirstOrDefault(
c => GenerateConstructorHelpers.CanDelegateTo(_semanticDocument, parameters, expressions, c));
if (delegatedConstructor != null)
{
// There was a constructor match in the base class. Synthesize a constructor of our own with
// the same parameter types that calls into that.
var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
members.Add(factory.CreateBaseDelegatingConstructor(delegatedConstructor, DetermineName()));
return;
}
}
// Otherwise, just generate a normal constructor that assigns any provided
// parameters into fields.
await AddFieldDelegatingConstructorAsync(argumentList, members, options).ConfigureAwait(false);
}
private void AddProperties(ArrayBuilder<ISymbol> members)
{
var typeInference = _semanticDocument.Document.GetLanguageService<ITypeInferenceService>();
foreach (var property in _state.PropertiesToGenerate)
{
if (_service.TryGenerateProperty(property, _semanticDocument.SemanticModel, typeInference, _cancellationToken, out var generatedProperty))
{
members.Add(generatedProperty);
}
}
}
private async Task AddFieldDelegatingConstructorAsync(
IList<TArgumentSyntax> argumentList, ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null)
{
var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken);
var parameterTypes = GetArgumentTypes(argumentList);
var parameterNames = _service.GenerateParameterNames(_semanticDocument.SemanticModel, argumentList, _cancellationToken);
using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters);
var parameterToExistingFieldMap = ImmutableDictionary.CreateBuilder<string, ISymbol>();
var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>();
var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
for (var i = 0; i < parameterNames.Count; i++)
{
var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]);
var parameterName = parameterNames[i];
var parameterType = parameterTypes[i];
parameterType = parameterType.RemoveUnavailableTypeParameters(
_semanticDocument.SemanticModel.Compilation, availableTypeParameters);
await FindExistingOrCreateNewMemberAsync(parameterName, parameterType, parameterToExistingFieldMap, parameterToNewFieldMap).ConfigureAwait(false);
parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default,
refKind: refKind,
isParams: false,
type: parameterType,
name: parameterName.BestNameForParameter));
}
// Empty Constructor for Struct is not allowed
if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure)))
{
members.AddRange(factory.CreateMemberDelegatingConstructor(
_semanticDocument.SemanticModel,
DetermineName(), null, parameters.ToImmutable(),
parameterToExistingFieldMap.ToImmutable(),
parameterToNewFieldMap.ToImmutable(),
addNullChecks: false,
preferThrowExpression: false,
generateProperties: false,
isContainedInUnsafeType: false)); // Since we generated the type, we know its not unsafe
}
}
private void AddExceptionConstructors(ArrayBuilder<ISymbol> members)
{
var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
var exceptionType = _semanticDocument.SemanticModel.Compilation.ExceptionType();
var constructors =
exceptionType.InstanceConstructors
.Where(c => c.DeclaredAccessibility is Accessibility.Public or Accessibility.Protected)
.Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: c.DeclaredAccessibility,
modifiers: default,
typeName: DetermineName(),
parameters: c.Parameters,
statements: default,
baseConstructorArguments: c.Parameters.Length == 0
? default
: factory.CreateArguments(c.Parameters)));
members.AddRange(constructors);
}
private ImmutableArray<AttributeData> DetermineAttributes()
{
if (_state.IsException)
{
var serializableType = _semanticDocument.SemanticModel.Compilation.SerializableAttributeType();
if (serializableType != null)
{
var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType);
return ImmutableArray.Create(attribute);
}
}
return default;
}
private Accessibility DetermineAccessibility()
=> _service.GetAccessibility(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken);
private static DeclarationModifiers DetermineModifiers()
=> default;
private INamedTypeSymbol DetermineBaseType()
{
if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
return null;
}
return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
}
private ImmutableArray<INamedTypeSymbol> DetermineInterfaces()
{
if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
if (type != null)
{
return ImmutableArray.Create(type);
}
}
return ImmutableArray<INamedTypeSymbol>.Empty;
}
private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type)
{
return type.RemoveUnavailableTypeParameters(
_semanticDocument.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol;
}
private string DetermineName()
=> GetTypeName(_state);
private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters()
=> _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken);
private TypeKind DetermineTypeKind()
{
return _state.IsStruct
? TypeKind.Struct
: _state.IsInterface
? TypeKind.Interface
: TypeKind.Class;
}
protected IList<ITypeParameterSymbol> GetAvailableTypeParameters()
{
var availableInnerTypeParameters = _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken);
var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null
? _state.TypeToGenerateInOpt.GetAllTypeParameters()
: SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList();
}
}
internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.GenerateType
{
internal abstract partial class AbstractGenerateTypeService<TService, TSimpleNameSyntax, TObjectCreationExpressionSyntax, TExpressionSyntax, TTypeDeclarationSyntax, TArgumentSyntax>
{
private partial class Editor
{
private async Task<INamedTypeSymbol> GenerateNamedTypeAsync()
{
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
DetermineAccessibility(),
DetermineModifiers(),
DetermineTypeKind(),
DetermineName(),
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: await DetermineMembersAsync().ConfigureAwait(false));
}
private async Task<INamedTypeSymbol> GenerateNamedTypeAsync(GenerateTypeOptionsResult options)
{
if (options.TypeKind == TypeKind.Delegate)
{
return CodeGenerationSymbolFactory.CreateDelegateTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
DetermineReturnType(),
RefKind.None,
name: options.TypeName,
typeParameters: DetermineTypeParametersWithDelegateChecks(),
parameters: DetermineParameters());
}
return CodeGenerationSymbolFactory.CreateNamedTypeSymbol(
DetermineAttributes(),
options.Accessibility,
DetermineModifiers(),
options.TypeKind,
options.TypeName,
DetermineTypeParameters(),
DetermineBaseType(),
DetermineInterfaces(),
members: await DetermineMembersAsync(options).ConfigureAwait(false));
}
private ITypeSymbol DetermineReturnType()
{
if (_state.DelegateMethodSymbol == null ||
_state.DelegateMethodSymbol.ReturnType == null ||
_state.DelegateMethodSymbol.ReturnType is IErrorTypeSymbol)
{
// Since we cannot determine the return type, we are returning void
return _state.Compilation.GetSpecialType(SpecialType.System_Void);
}
else
{
return _state.DelegateMethodSymbol.ReturnType;
}
}
private ImmutableArray<ITypeParameterSymbol> DetermineTypeParametersWithDelegateChecks()
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.TypeParameters;
}
// If the delegate symbol cannot be determined then
return DetermineTypeParameters();
}
private ImmutableArray<IParameterSymbol> DetermineParameters()
{
if (_state.DelegateMethodSymbol != null)
{
return _state.DelegateMethodSymbol.Parameters;
}
return default;
}
private async Task<ImmutableArray<ISymbol>> DetermineMembersAsync(GenerateTypeOptionsResult options = null)
{
using var _ = ArrayBuilder<ISymbol>.GetInstance(out var members);
await AddMembersAsync(members, options).ConfigureAwait(false);
if (_state.IsException)
AddExceptionConstructors(members);
return members.ToImmutable();
}
private async Task AddMembersAsync(ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null)
{
AddProperties(members);
if (!_service.TryGetArgumentList(_state.ObjectCreationExpressionOpt, out var argumentList))
{
return;
}
var parameterTypes = GetArgumentTypes(argumentList);
// Don't generate this constructor if it would conflict with a default exception
// constructor. Default exception constructors will be added automatically by our
// caller.
if (_state.IsException &&
_state.BaseTypeOrInterfaceOpt.InstanceConstructors.Any(
c => c.Parameters.Select(p => p.Type).SequenceEqual(parameterTypes, SymbolEqualityComparer.Default)))
{
return;
}
// If there's an accessible base constructor that would accept these types, then
// just call into that instead of generating fields.
if (_state.BaseTypeOrInterfaceOpt != null)
{
if (_state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface || argumentList.Count == 0)
{
// No need to add the default constructor if our base type is going to be 'object' or if we
// would be calling the empty constructor. We get that base constructor implicitly.
return;
}
// Synthesize some parameter symbols so we can see if these particular parameters could map to the
// parameters of any of the constructors we have in our base class. This will have the added
// benefit of allowing us to infer better types for complex type-less expressions (like lambdas).
var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
var refKinds = argumentList.SelectAsArray(a => syntaxFacts.GetRefKindOfArgument(a));
var parameters = parameterTypes.Zip(refKinds,
(t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray();
var expressions = GetArgumentExpressions(argumentList);
var delegatedConstructor = _state.BaseTypeOrInterfaceOpt.InstanceConstructors.FirstOrDefault(
c => GenerateConstructorHelpers.CanDelegateTo(_semanticDocument, parameters, expressions, c));
if (delegatedConstructor != null)
{
// There was a constructor match in the base class. Synthesize a constructor of our own with
// the same parameter types that calls into that.
var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
members.Add(factory.CreateBaseDelegatingConstructor(delegatedConstructor, DetermineName()));
return;
}
}
// Otherwise, just generate a normal constructor that assigns any provided
// parameters into fields.
await AddFieldDelegatingConstructorAsync(argumentList, members, options).ConfigureAwait(false);
}
private void AddProperties(ArrayBuilder<ISymbol> members)
{
var typeInference = _semanticDocument.Document.GetLanguageService<ITypeInferenceService>();
foreach (var property in _state.PropertiesToGenerate)
{
if (_service.TryGenerateProperty(property, _semanticDocument.SemanticModel, typeInference, _cancellationToken, out var generatedProperty))
{
members.Add(generatedProperty);
}
}
}
private async Task AddFieldDelegatingConstructorAsync(
IList<TArgumentSyntax> argumentList, ArrayBuilder<ISymbol> members, GenerateTypeOptionsResult options = null)
{
var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
var availableTypeParameters = _service.GetAvailableTypeParameters(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken);
var parameterTypes = GetArgumentTypes(argumentList);
var parameterNames = _service.GenerateParameterNames(_semanticDocument.SemanticModel, argumentList, _cancellationToken);
using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters);
var parameterToExistingFieldMap = ImmutableDictionary.CreateBuilder<string, ISymbol>();
var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>();
var syntaxFacts = _semanticDocument.Document.GetLanguageService<ISyntaxFactsService>();
for (var i = 0; i < parameterNames.Count; i++)
{
var refKind = syntaxFacts.GetRefKindOfArgument(argumentList[i]);
var parameterName = parameterNames[i];
var parameterType = parameterTypes[i];
parameterType = parameterType.RemoveUnavailableTypeParameters(
_semanticDocument.SemanticModel.Compilation, availableTypeParameters);
await FindExistingOrCreateNewMemberAsync(parameterName, parameterType, parameterToExistingFieldMap, parameterToNewFieldMap).ConfigureAwait(false);
parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol(
attributes: default,
refKind: refKind,
isParams: false,
type: parameterType,
name: parameterName.BestNameForParameter));
}
// Empty Constructor for Struct is not allowed
if (!(parameters.Count == 0 && options != null && (options.TypeKind == TypeKind.Struct || options.TypeKind == TypeKind.Structure)))
{
members.AddRange(factory.CreateMemberDelegatingConstructor(
_semanticDocument.SemanticModel,
DetermineName(), null, parameters.ToImmutable(),
parameterToExistingFieldMap.ToImmutable(),
parameterToNewFieldMap.ToImmutable(),
addNullChecks: false,
preferThrowExpression: false,
generateProperties: false,
isContainedInUnsafeType: false)); // Since we generated the type, we know its not unsafe
}
}
private void AddExceptionConstructors(ArrayBuilder<ISymbol> members)
{
var factory = _semanticDocument.Document.GetLanguageService<SyntaxGenerator>();
var exceptionType = _semanticDocument.SemanticModel.Compilation.ExceptionType();
var constructors =
exceptionType.InstanceConstructors
.Where(c => c.DeclaredAccessibility is Accessibility.Public or Accessibility.Protected)
.Select(c => CodeGenerationSymbolFactory.CreateConstructorSymbol(
attributes: default,
accessibility: c.DeclaredAccessibility,
modifiers: default,
typeName: DetermineName(),
parameters: c.Parameters,
statements: default,
baseConstructorArguments: c.Parameters.Length == 0
? default
: factory.CreateArguments(c.Parameters)));
members.AddRange(constructors);
}
private ImmutableArray<AttributeData> DetermineAttributes()
{
if (_state.IsException)
{
var serializableType = _semanticDocument.SemanticModel.Compilation.SerializableAttributeType();
if (serializableType != null)
{
var attribute = CodeGenerationSymbolFactory.CreateAttributeData(serializableType);
return ImmutableArray.Create(attribute);
}
}
return default;
}
private Accessibility DetermineAccessibility()
=> _service.GetAccessibility(_state, _semanticDocument.SemanticModel, _intoNamespace, _cancellationToken);
private static DeclarationModifiers DetermineModifiers()
=> default;
private INamedTypeSymbol DetermineBaseType()
{
if (_state.BaseTypeOrInterfaceOpt == null || _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
return null;
}
return RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
}
private ImmutableArray<INamedTypeSymbol> DetermineInterfaces()
{
if (_state.BaseTypeOrInterfaceOpt != null && _state.BaseTypeOrInterfaceOpt.TypeKind == TypeKind.Interface)
{
var type = RemoveUnavailableTypeParameters(_state.BaseTypeOrInterfaceOpt);
if (type != null)
{
return ImmutableArray.Create(type);
}
}
return ImmutableArray<INamedTypeSymbol>.Empty;
}
private INamedTypeSymbol RemoveUnavailableTypeParameters(INamedTypeSymbol type)
{
return type.RemoveUnavailableTypeParameters(
_semanticDocument.SemanticModel.Compilation, GetAvailableTypeParameters()) as INamedTypeSymbol;
}
private string DetermineName()
=> GetTypeName(_state);
private ImmutableArray<ITypeParameterSymbol> DetermineTypeParameters()
=> _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken);
private TypeKind DetermineTypeKind()
{
return _state.IsStruct
? TypeKind.Struct
: _state.IsInterface
? TypeKind.Interface
: TypeKind.Class;
}
protected IList<ITypeParameterSymbol> GetAvailableTypeParameters()
{
var availableInnerTypeParameters = _service.GetTypeParameters(_state, _semanticDocument.SemanticModel, _cancellationToken);
var availableOuterTypeParameters = !_intoNamespace && _state.TypeToGenerateInOpt != null
? _state.TypeToGenerateInOpt.GetAllTypeParameters()
: SpecializedCollections.EmptyEnumerable<ITypeParameterSymbol>();
return availableOuterTypeParameters.Concat(availableInnerTypeParameters).ToList();
}
}
internal abstract bool TryGenerateProperty(TSimpleNameSyntax propertyName, SemanticModel semanticModel, ITypeInferenceService typeInference, CancellationToken cancellationToken, out IPropertySymbol property);
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/Implementation/Classification/SyntacticClassificationTaggerProvider.TagComputer.LastLineCache.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification
{
internal partial class SyntacticClassificationTaggerProvider
{
internal partial class TagComputer
{
/// <summary>
/// it is a helper class that encapsulates logic on holding onto last classification result
/// </summary>
private class LastLineCache : ForegroundThreadAffinitizedObject
{
// this helper class is primarily to improve active typing perf. don't bother to cache
// something very big.
private const int MaxClassificationNumber = 32;
// mutating state
private SnapshotSpan _span;
private readonly ArrayBuilder<ClassifiedSpan> _classifications = new();
public LastLineCache(IThreadingContext threadingContext) : base(threadingContext)
{
}
private void Clear()
{
this.AssertIsForeground();
_span = default;
_classifications.Clear();
}
public bool TryUseCache(SnapshotSpan span, ArrayBuilder<ClassifiedSpan> classifications)
{
this.AssertIsForeground();
// currently, it is using SnapshotSpan even though holding onto it could be
// expensive. reason being it should be very soon sync-ed to latest snapshot.
if (_span.Equals(span))
{
classifications.AddRange(_classifications);
return true;
}
this.Clear();
return false;
}
public void Update(SnapshotSpan span, ArrayBuilder<ClassifiedSpan> classifications)
{
this.AssertIsForeground();
this.Clear();
if (classifications.Count < MaxClassificationNumber)
{
_span = span;
_classifications.AddRange(classifications);
}
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Classification
{
internal partial class SyntacticClassificationTaggerProvider
{
internal partial class TagComputer
{
/// <summary>
/// it is a helper class that encapsulates logic on holding onto last classification result
/// </summary>
private class LastLineCache : ForegroundThreadAffinitizedObject
{
// this helper class is primarily to improve active typing perf. don't bother to cache
// something very big.
private const int MaxClassificationNumber = 32;
// mutating state
private SnapshotSpan _span;
private readonly ArrayBuilder<ClassifiedSpan> _classifications = new();
public LastLineCache(IThreadingContext threadingContext) : base(threadingContext)
{
}
private void Clear()
{
this.AssertIsForeground();
_span = default;
_classifications.Clear();
}
public bool TryUseCache(SnapshotSpan span, ArrayBuilder<ClassifiedSpan> classifications)
{
this.AssertIsForeground();
// currently, it is using SnapshotSpan even though holding onto it could be
// expensive. reason being it should be very soon sync-ed to latest snapshot.
if (_span.Equals(span))
{
classifications.AddRange(_classifications);
return true;
}
this.Clear();
return false;
}
public void Update(SnapshotSpan span, ArrayBuilder<ClassifiedSpan> classifications)
{
this.AssertIsForeground();
this.Clear();
if (classifications.Count < MaxClassificationNumber)
{
_span = span;
_classifications.AddRange(classifications);
}
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/Shared/Tagging/EventSources/TaggerEventSources.DocumentActiveContextChangedEventSource.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class DocumentActiveContextChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
{
public DocumentActiveContextChangedEventSource(ITextBuffer subjectBuffer)
: base(subjectBuffer)
{
}
protected override void ConnectToWorkspace(Workspace workspace)
=> workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged;
protected override void DisconnectFromWorkspace(Workspace workspace)
=> workspace.DocumentActiveContextChanged -= OnDocumentActiveContextChanged;
private void OnDocumentActiveContextChanged(object? sender, DocumentActiveContextChangedEventArgs e)
{
var document = SubjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
if (document != null && document.Id == e.NewActiveContextDocumentId)
{
this.RaiseChanged();
}
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Editor.Tagging;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
namespace Microsoft.CodeAnalysis.Editor.Shared.Tagging
{
internal partial class TaggerEventSources
{
private class DocumentActiveContextChangedEventSource : AbstractWorkspaceTrackingTaggerEventSource
{
public DocumentActiveContextChangedEventSource(ITextBuffer subjectBuffer)
: base(subjectBuffer)
{
}
protected override void ConnectToWorkspace(Workspace workspace)
=> workspace.DocumentActiveContextChanged += OnDocumentActiveContextChanged;
protected override void DisconnectFromWorkspace(Workspace workspace)
=> workspace.DocumentActiveContextChanged -= OnDocumentActiveContextChanged;
private void OnDocumentActiveContextChanged(object? sender, DocumentActiveContextChangedEventArgs e)
{
var document = SubjectBuffer.AsTextContainer().GetOpenDocumentInCurrentContext();
if (document != null && document.Id == e.NewActiveContextDocumentId)
{
this.RaiseChanged();
}
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/EditorConfigSettings/DataProvider/CodeStyle/CommonCodeStyleSettingsWorkspaceServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider.CodeStyle
{
[ExportWorkspaceServiceFactory(typeof(IWorkspaceSettingsProviderFactory<CodeStyleSetting>)), Shared]
internal class CommonCodeStyleSettingsWorkspaceServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CommonCodeStyleSettingsWorkspaceServiceFactory() { }
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new CommonCodeStyleSettingsProviderFactory(workspaceServices.Workspace);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Editor.EditorConfigSettings.Data;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Editor.EditorConfigSettings.DataProvider.CodeStyle
{
[ExportWorkspaceServiceFactory(typeof(IWorkspaceSettingsProviderFactory<CodeStyleSetting>)), Shared]
internal class CommonCodeStyleSettingsWorkspaceServiceFactory : IWorkspaceServiceFactory
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public CommonCodeStyleSettingsWorkspaceServiceFactory() { }
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
=> new CommonCodeStyleSettingsProviderFactory(workspaceServices.Workspace);
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDeconstructionAssignmentOperation.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDeconstructionAssignmentOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_01()
{
string source = @"
class C
{
void M(bool b, int i1, int i2, int i3, int i4, int i5, int i6)
/*<bind>*/{
(i1, i2) = b ? (i3, i4) : (i5, i6);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(i3, i4)')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: '(i3, i4)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i3, System.Int32 i4)) (Syntax: '(i3, i4)')
NaturalType: (System.Int32 i3, System.Int32 i4)
Elements(2):
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(i5, i6)')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: '(i5, i6)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i5, System.Int32 i6)) (Syntax: '(i5, i6)')
NaturalType: (System.Int32 i5, System.Int32 i6)
Elements(2):
IParameterReferenceOperation: i5 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i5')
IParameterReferenceOperation: i6 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i6')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(i1, i2) = ... : (i5, i6);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2) = ... : (i5, i6)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (i3, i4) : (i5, i6)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_02()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
(var i1, var i2) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(var i1, va ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(var i1, va ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(var i1, var i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i2')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_03()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
var (i1, i2) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'var (i1, i2 ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2 ... 2) : (3, 4)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_04()
{
string source = @"
class C
{
void M(bool b, C c1)
/*<bind>*/{
var (i1, i2) = b ? this : c1;
}/*</bind>*/
public void Deconstruct(out int i1, out int i2)
{
i1 = 1;
i2 = 2;
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'var (i1, i2 ... this : c1;')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2 ... ? this : c1')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'b ? this : c1')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MixedDeconstruction()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
int i2;
(int i1, i2) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedOperationTree = @"
IBlockOperation (2 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 i2
Local_2: System.Int32 i1
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i2;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i2')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2')
Initializer:
null
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, i2 ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2 ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IConditionalOperation (OperationKind.Conditional, Type: (System.Int32, System.Int32)) (Syntax: 'b ? (1, 2) : (3, 4)')
Condition:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
WhenTrue:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
WhenFalse:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i2] [System.Int32 i1]
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, i2 ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2 ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MixedNestedDeconstruction()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
int i2;
(int i1, (i2, int i3)) = b ? (1, (2, 3)) : (4, (5, 6));
}/*</bind>*/
}";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedOperationTree = @"
IBlockOperation (2 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 i2
Local_2: System.Int32 i1
Local_3: System.Int32 i3
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i2;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i2')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2')
Initializer:
null
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, (i ... 4, (5, 6));')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i ... (4, (5, 6))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i2, int i3))')
NaturalType: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i2, System.Int32 i3)) (Syntax: '(i2, int i3)')
NaturalType: (System.Int32 i2, System.Int32 i3)
Elements(2):
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i3')
ILocalReferenceOperation: i3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3')
Right:
IConditionalOperation (OperationKind.Conditional, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: 'b ? (1, (2, ... (4, (5, 6))')
Condition:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
WhenTrue:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
WhenFalse:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(4, (5, 6))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(5, 6)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i2] [System.Int32 i1] [System.Int32 i3]
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, (2, 3))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(4, (5, 6))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(4, (5, 6))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(5, 6)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, (i ... 4, (5, 6));')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i ... (4, (5, 6))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i2, int i3))')
NaturalType: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i2, System.Int32 i3)) (Syntax: '(i2, int i3)')
NaturalType: (System.Int32 i2, System.Int32 i3)
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i3')
ILocalReferenceOperation: i3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 'b ? (1, (2, ... (4, (5, 6))')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_06()
{
string source = @"
class C
{
int fI1 = 0;
void M(bool b, C c1, int i1)
/*<bind>*/{
(c1?.fI1, i1) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0131: The left-hand side of an assignment must be a variable, property or indexer
// (c1?.fI1, i1) = b ? (1, 2) : (3, 4);
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "c1?.fI1").WithLocation(7, 10),
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0]
.locals {R3}
{
CaptureIds: [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '.fI1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: '.fI1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IFieldReferenceOperation: System.Int32 C.fI1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: '.fI1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
Children(1):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '(c1?.fI1, i ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32? fI1, System.Int32 i1), IsInvalid) (Syntax: '(c1?.fI1, i ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32? fI1, System.Int32 i1), IsInvalid) (Syntax: '(c1?.fI1, i1)')
NaturalType: (System.Int32? fI1, System.Int32 i1)
Elements(2):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_07()
{
string source = @"
class C
{
void M(bool b, int i1, int i2, int i3)
/*<bind>*/{
(i1, (i2, i3)) = b ? (1, (2, 3)) : (4, (5, 6));
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, (2, 3))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(4, (5, 6))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(4, (5, 6))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(5, 6)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(i1, (i2, i ... 4, (5, 6));')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(i1, (i2, i ... (4, (5, 6))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(i1, (i2, i3))')
NaturalType: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i2, System.Int32 i3)) (Syntax: '(i2, i3)')
NaturalType: (System.Int32 i2, System.Int32 i3)
Elements(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 'b ? (1, (2, ... (4, (5, 6))')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_08()
{
string source = @"
class C
{
void M(int i1, int i2, int i3, int i4, int i5, int? i6, int i7)
/*<bind>*/
{
((i1, i2), i3) = ((i4, i5), i6 ?? i7);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3] [4] [6]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i4')
Value:
IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i5')
Value:
IParameterReferenceOperation: i5 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i5')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i6')
Value:
IParameterReferenceOperation: i6 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i6')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i6')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i6')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i6')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i6')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i6')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i7')
Value:
IParameterReferenceOperation: i7 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i7')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '((i1, i2), ... i6 ?? i7);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ((System.Int32 i1, System.Int32 i2), System.Int32 i3)) (Syntax: '((i1, i2), ... , i6 ?? i7)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((System.Int32 i1, System.Int32 i2), System.Int32 i3)) (Syntax: '((i1, i2), i3)')
NaturalType: ((System.Int32 i1, System.Int32 i2), System.Int32 i3)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ((System.Int32, System.Int32), System.Int32), IsImplicit) (Syntax: '((i4, i5), i6 ?? i7)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
ITupleOperation (OperationKind.Tuple, Type: ((System.Int32 i4, System.Int32 i5), System.Int32)) (Syntax: '((i4, i5), i6 ?? i7)')
NaturalType: ((System.Int32 i4, System.Int32 i5), System.Int32)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i4, System.Int32 i5)) (Syntax: '(i4, i5)')
NaturalType: (System.Int32 i4, System.Int32 i5)
Elements(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i4')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i5')
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i6 ?? i7')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDeconstructionAssignmentOperation : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_01()
{
string source = @"
class C
{
void M(bool b, int i1, int i2, int i3, int i4, int i5, int i6)
/*<bind>*/{
(i1, i2) = b ? (i3, i4) : (i5, i6);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2]
Block[B1] - Block
Predecessors: [B0]
Statements (2)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(i3, i4)')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: '(i3, i4)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i3, System.Int32 i4)) (Syntax: '(i3, i4)')
NaturalType: (System.Int32 i3, System.Int32 i4)
Elements(2):
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(i5, i6)')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: '(i5, i6)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i5, System.Int32 i6)) (Syntax: '(i5, i6)')
NaturalType: (System.Int32 i5, System.Int32 i6)
Elements(2):
IParameterReferenceOperation: i5 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i5')
IParameterReferenceOperation: i6 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i6')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(i1, i2) = ... : (i5, i6);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2) = ... : (i5, i6)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (i3, i4) : (i5, i6)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_02()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
(var i1, var i2) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(var i1, va ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(var i1, va ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(var i1, var i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'var i2')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_03()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
var (i1, i2) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'var (i1, i2 ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2 ... 2) : (3, 4)')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_04()
{
string source = @"
class C
{
void M(bool b, C c1)
/*<bind>*/{
var (i1, i2) = b ? this : c1;
}/*</bind>*/
public void Deconstruct(out int i1, out int i2)
{
i1 = 1;
i2 = 2;
}
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i1] [System.Int32 i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'this')
Value:
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: C) (Syntax: 'this')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C) (Syntax: 'c1')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: 'var (i1, i2 ... this : c1;')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2 ... ? this : c1')
Left:
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: 'var (i1, i2)')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: C, IsImplicit) (Syntax: 'b ? this : c1')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MixedDeconstruction()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
int i2;
(int i1, i2) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedOperationTree = @"
IBlockOperation (2 statements, 2 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 i2
Local_2: System.Int32 i1
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i2;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i2')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2')
Initializer:
null
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, i2 ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2 ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Right:
IConditionalOperation (OperationKind.Conditional, Type: (System.Int32, System.Int32)) (Syntax: 'b ? (1, 2) : (3, 4)')
Condition:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
WhenTrue:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
WhenFalse:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i2] [System.Int32 i1]
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, i2 ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2 ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(int i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void MixedNestedDeconstruction()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
int i2;
(int i1, (i2, int i3)) = b ? (1, (2, 3)) : (4, (5, 6));
}/*</bind>*/
}";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedOperationTree = @"
IBlockOperation (2 statements, 3 locals) (OperationKind.Block, Type: null) (Syntax: '{ ... }')
Locals: Local_1: System.Int32 i2
Local_2: System.Int32 i1
Local_3: System.Int32 i3
IVariableDeclarationGroupOperation (1 declarations) (OperationKind.VariableDeclarationGroup, Type: null) (Syntax: 'int i2;')
IVariableDeclarationOperation (1 declarators) (OperationKind.VariableDeclaration, Type: null) (Syntax: 'int i2')
Declarators:
IVariableDeclaratorOperation (Symbol: System.Int32 i2) (OperationKind.VariableDeclarator, Type: null) (Syntax: 'i2')
Initializer:
null
Initializer:
null
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, (i ... 4, (5, 6));')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i ... (4, (5, 6))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i2, int i3))')
NaturalType: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i2, System.Int32 i3)) (Syntax: '(i2, int i3)')
NaturalType: (System.Int32 i2, System.Int32 i3)
Elements(2):
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i3')
ILocalReferenceOperation: i3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3')
Right:
IConditionalOperation (OperationKind.Conditional, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: 'b ? (1, (2, ... (4, (5, 6))')
Condition:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
WhenTrue:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
WhenFalse:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(4, (5, 6))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(5, 6)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')";
VerifyOperationTreeAndDiagnosticsForTest<BlockSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [System.Int32 i2] [System.Int32 i1] [System.Int32 i3]
CaptureIds: [0] [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
ILocalReferenceOperation: i2 (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i2')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, (2, 3))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(4, (5, 6))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(4, (5, 6))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(5, 6)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(int i1, (i ... 4, (5, 6));')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i ... (4, (5, 6))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(int i1, (i2, int i3))')
NaturalType: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))
Elements(2):
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i2, System.Int32 i3)) (Syntax: '(i2, int i3)')
NaturalType: (System.Int32 i2, System.Int32 i3)
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: System.Int32) (Syntax: 'int i3')
ILocalReferenceOperation: i3 (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32) (Syntax: 'i3')
Right:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 'b ? (1, (2, ... (4, (5, 6))')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics, parseOptions: TestOptions.RegularPreview);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_06()
{
string source = @"
class C
{
int fI1 = 0;
void M(bool b, C c1, int i1)
/*<bind>*/{
(c1?.fI1, i1) = b ? (1, 2) : (3, 4);
}/*</bind>*/
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0131: The left-hand side of an assignment must be a variable, property or indexer
// (c1?.fI1, i1) = b ? (1, 2) : (3, 4);
Diagnostic(ErrorCode.ERR_AssgLvalueExpected, "c1?.fI1").WithLocation(7, 10),
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1} {R2} {R3}
.locals {R1}
{
CaptureIds: [2] [3] [4]
.locals {R2}
{
CaptureIds: [0]
.locals {R3}
{
CaptureIds: [1]
Block[B1] - Block
Predecessors: [B0]
Statements (1)
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IParameterReferenceOperation: c1 (OperationKind.ParameterReference, Type: C, IsInvalid) (Syntax: 'c1')
Jump if True (Regular) to Block[B3]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsInvalid, IsImplicit) (Syntax: 'c1')
Operand:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Leaving: {R3}
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '.fI1')
Value:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: '.fI1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(ImplicitNullable)
Operand:
IFieldReferenceOperation: System.Int32 C.fI1 (OperationKind.FieldReference, Type: System.Int32, IsInvalid) (Syntax: '.fI1')
Instance Receiver:
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: C, IsInvalid, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Leaving: {R3}
}
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1')
Value:
IDefaultValueOperation (OperationKind.DefaultValue, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
Value:
IInvalidOperation (OperationKind.Invalid, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
Children(1):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B5] - Block
Predecessors: [B4]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
Jump if False (Regular) to Block[B7]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B6]
Block[B6] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, 2)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(1, 2)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
Next (Regular) Block[B8]
Block[B7] - Block
Predecessors: [B5]
Statements (1)
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(3, 4)')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(3, 4)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Next (Regular) Block[B8]
Block[B8] - Block
Predecessors: [B6] [B7]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: '(c1?.fI1, i ... ) : (3, 4);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32? fI1, System.Int32 i1), IsInvalid) (Syntax: '(c1?.fI1, i ... 2) : (3, 4)')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32? fI1, System.Int32 i1), IsInvalid) (Syntax: '(c1?.fI1, i1)')
NaturalType: (System.Int32? fI1, System.Int32 i1)
Elements(2):
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsInvalid, IsImplicit) (Syntax: 'c1?.fI1')
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
Right:
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: (System.Int32, System.Int32), IsImplicit) (Syntax: 'b ? (1, 2) : (3, 4)')
Next (Regular) Block[B9]
Leaving: {R1}
}
Block[B9] - Exit
Predecessors: [B8]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_07()
{
string source = @"
class C
{
void M(bool b, int i1, int i2, int i3)
/*<bind>*/{
(i1, (i2, i3)) = b ? (1, (2, 3)) : (4, (5, 6));
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3]
Block[B1] - Block
Predecessors: [B0]
Statements (3)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(1, (2, 3))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(1, (2, 3))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(2, 3)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: '(4, (5, 6))')
Value:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, (System.Int32, System.Int32))) (Syntax: '(4, (5, 6))')
NaturalType: (System.Int32, (System.Int32, System.Int32))
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32, System.Int32)) (Syntax: '(5, 6)')
NaturalType: (System.Int32, System.Int32)
Elements(2):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '(i1, (i2, i ... 4, (5, 6));')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(i1, (i2, i ... (4, (5, 6))')
Left:
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))) (Syntax: '(i1, (i2, i3))')
NaturalType: (System.Int32 i1, (System.Int32 i2, System.Int32 i3))
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i2, System.Int32 i3)) (Syntax: '(i2, i3)')
NaturalType: (System.Int32 i2, System.Int32 i3)
Elements(2):
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Right:
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: (System.Int32, (System.Int32, System.Int32)), IsImplicit) (Syntax: 'b ? (1, (2, ... (4, (5, 6))')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeconstructionFlow_08()
{
string source = @"
class C
{
void M(int i1, int i2, int i3, int i4, int i5, int? i6, int i7)
/*<bind>*/
{
((i1, i2), i3) = ((i4, i5), i6 ?? i7);
}/*</bind>*/
}
";
var expectedDiagnostics = DiagnosticDescription.None;
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
CaptureIds: [0] [1] [2] [3] [4] [6]
Block[B1] - Block
Predecessors: [B0]
Statements (5)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i1')
Value:
IParameterReferenceOperation: i1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i1')
IFlowCaptureOperation: 1 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i2')
Value:
IParameterReferenceOperation: i2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i2')
IFlowCaptureOperation: 2 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i3')
Value:
IParameterReferenceOperation: i3 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i3')
IFlowCaptureOperation: 3 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i4')
Value:
IParameterReferenceOperation: i4 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i4')
IFlowCaptureOperation: 4 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i5')
Value:
IParameterReferenceOperation: i5 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i5')
Next (Regular) Block[B2]
Entering: {R2}
.locals {R2}
{
CaptureIds: [5]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 5 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i6')
Value:
IParameterReferenceOperation: i6 (OperationKind.ParameterReference, Type: System.Int32?) (Syntax: 'i6')
Jump if True (Regular) to Block[B4]
IIsNullOperation (OperationKind.IsNull, Type: System.Boolean, IsImplicit) (Syntax: 'i6')
Operand:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i6')
Leaving: {R2}
Next (Regular) Block[B3]
Block[B3] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i6')
Value:
IInvocationOperation ( System.Int32 System.Int32?.GetValueOrDefault()) (OperationKind.Invocation, Type: System.Int32, IsImplicit) (Syntax: 'i6')
Instance Receiver:
IFlowCaptureReferenceOperation: 5 (OperationKind.FlowCaptureReference, Type: System.Int32?, IsImplicit) (Syntax: 'i6')
Arguments(0)
Next (Regular) Block[B5]
Leaving: {R2}
}
Block[B4] - Block
Predecessors: [B2]
Statements (1)
IFlowCaptureOperation: 6 (OperationKind.FlowCapture, Type: null, IsImplicit) (Syntax: 'i7')
Value:
IParameterReferenceOperation: i7 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i7')
Next (Regular) Block[B5]
Block[B5] - Block
Predecessors: [B3] [B4]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null) (Syntax: '((i1, i2), ... i6 ?? i7);')
Expression:
IDeconstructionAssignmentOperation (OperationKind.DeconstructionAssignment, Type: ((System.Int32 i1, System.Int32 i2), System.Int32 i3)) (Syntax: '((i1, i2), ... , i6 ?? i7)')
Left:
ITupleOperation (OperationKind.Tuple, Type: ((System.Int32 i1, System.Int32 i2), System.Int32 i3)) (Syntax: '((i1, i2), i3)')
NaturalType: ((System.Int32 i1, System.Int32 i2), System.Int32 i3)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i1, System.Int32 i2)) (Syntax: '(i1, i2)')
NaturalType: (System.Int32 i1, System.Int32 i2)
Elements(2):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i1')
IFlowCaptureReferenceOperation: 1 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i2')
IFlowCaptureReferenceOperation: 2 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i3')
Right:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: ((System.Int32, System.Int32), System.Int32), IsImplicit) (Syntax: '((i4, i5), i6 ?? i7)')
Conversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
(Identity)
Operand:
ITupleOperation (OperationKind.Tuple, Type: ((System.Int32 i4, System.Int32 i5), System.Int32)) (Syntax: '((i4, i5), i6 ?? i7)')
NaturalType: ((System.Int32 i4, System.Int32 i5), System.Int32)
Elements(2):
ITupleOperation (OperationKind.Tuple, Type: (System.Int32 i4, System.Int32 i5)) (Syntax: '(i4, i5)')
NaturalType: (System.Int32 i4, System.Int32 i5)
Elements(2):
IFlowCaptureReferenceOperation: 3 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i4')
IFlowCaptureReferenceOperation: 4 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i5')
IFlowCaptureReferenceOperation: 6 (OperationKind.FlowCaptureReference, Type: System.Int32, IsImplicit) (Syntax: 'i6 ?? i7')
Next (Regular) Block[B6]
Leaving: {R1}
}
Block[B6] - Exit
Predecessors: [B5]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/CSharpTest/KeywordHighlighting/IfStatementHighlighterTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class IfStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(IfStatementHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndSingleElse1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndSingleElse2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElse1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElse2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElse3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else|]
[|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else|]|}
[|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|]
{|Cursor:[|if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines4()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|]
[|if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElseTouching1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|}(a < 5)
{
// blah
}
[|else if|](a == 10)
{
// blah
}
[|else|]{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElseTouching2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|](a < 5)
{
// blah
}
{|Cursor:[|else if|]|}(a == 10)
{
// blah
}
[|else|]{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElseTouching3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|](a < 5)
{
// blah
}
[|else if|](a == 10)
{
// blah
}
{|Cursor:[|else|]|}{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExtraSpacesBetweenElseAndIf1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExtraSpacesBetweenElseAndIf2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExtraSpacesBetweenElseAndIf3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else|] /* test */ [|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else|]|} /* test */ [|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|] /* test */ {|Cursor:[|if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf4()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|] /* test */ [|if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestNestedIfDoesNotHighlight1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
int b = 15;
{|Cursor:[|if|]|} (a < 5)
{
// blah
if (b < 15)
b = 15;
else
b = 14;
}
[|else if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestNestedIfDoesNotHighlight2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
int b = 15;
[|if|] (a < 5)
{
// blah
if (b < 15)
b = 15;
else
b = 14;
}
{|Cursor:[|else if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestNestedIfDoesNotHighlight3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
int b = 15;
[|if|] (a < 5)
{
// blah
if (b < 15)
b = 15;
else
b = 14;
}
[|else if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"class C
{
void M()
{
{|Cursor:[|if|]|} (x)
{
if (y)
{
F();
}
else if (z)
{
G();
}
else
{
H();
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_1()
{
await TestAsync(
@"class C
{
void M()
{
if (x)
{
{|Cursor:[|if|]|} (y)
{
F();
}
[|else if|] (z)
{
G();
}
[|else|]
{
H();
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_2()
{
await TestAsync(
@"class C
{
void M()
{
if (x)
{
[|if|] (y)
{
F();
}
{|Cursor:[|else if|]|} (z)
{
G();
}
[|else|]
{
H();
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_3()
{
await TestAsync(
@"class C
{
void M()
{
if (x)
{
[|if|] (y)
{
F();
}
[|else if|] (z)
{
G();
}
{|Cursor:[|else|]|}
{
H();
}
}
}
}");
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.KeywordHighlighting
{
public class IfStatementHighlighterTests : AbstractCSharpKeywordHighlighterTests
{
internal override Type GetHighlighterType()
=> typeof(IfStatementHighlighter);
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndSingleElse1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndSingleElse2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElse1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElse2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElse3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else|]
[|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else|]|}
[|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|]
{|Cursor:[|if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithElseIfOnDifferentLines4()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|]
[|if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElseTouching1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|}(a < 5)
{
// blah
}
[|else if|](a == 10)
{
// blah
}
[|else|]{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElseTouching2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|](a < 5)
{
// blah
}
{|Cursor:[|else if|]|}(a == 10)
{
// blah
}
[|else|]{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestIfStatementWithIfAndElseIfAndElseTouching3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|](a < 5)
{
// blah
}
[|else if|](a == 10)
{
// blah
}
{|Cursor:[|else|]|}{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExtraSpacesBetweenElseAndIf1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExtraSpacesBetweenElseAndIf2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExtraSpacesBetweenElseAndIf3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
{|Cursor:[|if|]|} (a < 5)
{
// blah
}
[|else|] /* test */ [|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
{|Cursor:[|else|]|} /* test */ [|if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|] /* test */ {|Cursor:[|if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestCommentBetweenElseIf4()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
[|if|] (a < 5)
{
// blah
}
[|else|] /* test */ [|if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestNestedIfDoesNotHighlight1()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
int b = 15;
{|Cursor:[|if|]|} (a < 5)
{
// blah
if (b < 15)
b = 15;
else
b = 14;
}
[|else if|] (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestNestedIfDoesNotHighlight2()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
int b = 15;
[|if|] (a < 5)
{
// blah
if (b < 15)
b = 15;
else
b = 14;
}
{|Cursor:[|else if|]|} (a == 10)
{
// blah
}
[|else|]
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestNestedIfDoesNotHighlight3()
{
await TestAsync(
@"public class C
{
public void Goo()
{
int a = 10;
int b = 15;
[|if|] (a < 5)
{
// blah
if (b < 15)
b = 15;
else
b = 14;
}
[|else if|] (a == 10)
{
// blah
}
{|Cursor:[|else|]|}
{
// blah
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample1_1()
{
await TestAsync(
@"class C
{
void M()
{
{|Cursor:[|if|]|} (x)
{
if (y)
{
F();
}
else if (z)
{
G();
}
else
{
H();
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_1()
{
await TestAsync(
@"class C
{
void M()
{
if (x)
{
{|Cursor:[|if|]|} (y)
{
F();
}
[|else if|] (z)
{
G();
}
[|else|]
{
H();
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_2()
{
await TestAsync(
@"class C
{
void M()
{
if (x)
{
[|if|] (y)
{
F();
}
{|Cursor:[|else if|]|} (z)
{
G();
}
[|else|]
{
H();
}
}
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.KeywordHighlighting)]
public async Task TestExample2_3()
{
await TestAsync(
@"class C
{
void M()
{
if (x)
{
[|if|] (y)
{
F();
}
[|else if|] (z)
{
G();
}
{|Cursor:[|else|]|}
{
H();
}
}
}
}");
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/Core/Portable/InvertConditional/AbstractInvertConditionalCodeRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.InvertConditional
{
internal abstract class AbstractInvertConditionalCodeRefactoringProvider<TConditionalExpressionSyntax>
: CodeRefactoringProvider
where TConditionalExpressionSyntax : SyntaxNode
{
protected abstract bool ShouldOffer(TConditionalExpressionSyntax conditional);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false);
if (conditional == null || !ShouldOffer(conditional))
{
return;
}
context.RegisterRefactoring(new MyCodeAction(
c => InvertConditionalAsync(document, span, c)),
conditional.Span);
}
private static async Task<TConditionalExpressionSyntax?> FindConditionalAsync(
Document document, TextSpan span, CancellationToken cancellationToken)
=> await document.TryGetRelevantNodeAsync<TConditionalExpressionSyntax>(span, cancellationToken).ConfigureAwait(false);
private static async Task<Document> InvertConditionalAsync(
Document document, TextSpan span, CancellationToken cancellationToken)
{
var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(conditional);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
editor.Generator.SyntaxFacts.GetPartsOfConditionalExpression(conditional,
out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(condition, editor.Generator.Negate(editor.Generator.SyntaxGeneratorInternal, condition, semanticModel, cancellationToken));
editor.ReplaceNode(whenTrue, whenFalse.WithTriviaFrom(whenTrue));
editor.ReplaceNode(whenFalse, whenTrue.WithTriviaFrom(whenFalse));
return document.WithSyntaxRoot(editor.GetChangedRoot());
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Invert_conditional, createChangedDocument, nameof(FeaturesResources.Invert_conditional))
{
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.InvertConditional
{
internal abstract class AbstractInvertConditionalCodeRefactoringProvider<TConditionalExpressionSyntax>
: CodeRefactoringProvider
where TConditionalExpressionSyntax : SyntaxNode
{
protected abstract bool ShouldOffer(TConditionalExpressionSyntax conditional);
public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var (document, span, cancellationToken) = context;
var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false);
if (conditional == null || !ShouldOffer(conditional))
{
return;
}
context.RegisterRefactoring(new MyCodeAction(
c => InvertConditionalAsync(document, span, c)),
conditional.Span);
}
private static async Task<TConditionalExpressionSyntax?> FindConditionalAsync(
Document document, TextSpan span, CancellationToken cancellationToken)
=> await document.TryGetRelevantNodeAsync<TConditionalExpressionSyntax>(span, cancellationToken).ConfigureAwait(false);
private static async Task<Document> InvertConditionalAsync(
Document document, TextSpan span, CancellationToken cancellationToken)
{
var conditional = await FindConditionalAsync(document, span, cancellationToken).ConfigureAwait(false);
Contract.ThrowIfNull(conditional);
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var editor = new SyntaxEditor(root, document.Project.Solution.Workspace);
editor.Generator.SyntaxFacts.GetPartsOfConditionalExpression(conditional,
out var condition, out var whenTrue, out var whenFalse);
editor.ReplaceNode(condition, editor.Generator.Negate(editor.Generator.SyntaxGeneratorInternal, condition, semanticModel, cancellationToken));
editor.ReplaceNode(whenTrue, whenFalse.WithTriviaFrom(whenTrue));
editor.ReplaceNode(whenFalse, whenTrue.WithTriviaFrom(whenFalse));
return document.WithSyntaxRoot(editor.GetChangedRoot());
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument)
: base(FeaturesResources.Invert_conditional, createChangedDocument, nameof(FeaturesResources.Invert_conditional))
{
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/CSharp/Portable/Emitter/Model/PEAssemblyBuilder.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, Cci.IAssemblyReference
{
private readonly SourceAssemblySymbol _sourceAssembly;
/// <summary>
/// Additional types injected by the Expression Evaluator.
/// </summary>
private readonly ImmutableArray<NamedTypeSymbol> _additionalTypes;
private ImmutableArray<Cci.IFileReference> _lazyFiles;
/// <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary>
private ImmutableArray<Cci.IFileReference> _lazyFilesWithoutManifestResources;
private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute;
private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute;
private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute;
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute;
private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute;
/// <summary>
/// The behavior of the C# command-line compiler is as follows:
/// 1) If the /out switch is specified, then the explicit assembly name is used.
/// 2) Otherwise,
/// a) if the assembly is executable, then the assembly name is derived from
/// the name of the file containing the entrypoint;
/// b) otherwise, the assembly name is derived from the name of the first input
/// file.
///
/// Since we don't know which method is the entrypoint until well after the
/// SourceAssemblySymbol is created, in case 2a, its name will not reflect the
/// name of the file containing the entrypoint. We leave it to our caller to
/// provide that name explicitly.
/// </summary>
/// <remarks>
/// In cases 1 and 2b, we expect (metadataName == sourceAssembly.MetadataName).
/// </remarks>
private readonly string _metadataName;
public PEAssemblyBuilderBase(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources,
ImmutableArray<NamedTypeSymbol> additionalTypes)
: base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources)
{
Debug.Assert(sourceAssembly is object);
_sourceAssembly = sourceAssembly;
_additionalTypes = additionalTypes.NullToEmpty();
_metadataName = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null);
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
}
public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt
=> _sourceAssembly;
public sealed override ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes()
=> _additionalTypes;
internal sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance();
CreateEmbeddedAttributesIfNeeded(diagnostics);
builder.AddIfNotNull(_lazyEmbeddedAttribute);
builder.AddIfNotNull(_lazyIsReadOnlyAttribute);
builder.AddIfNotNull(_lazyIsUnmanagedAttribute);
builder.AddIfNotNull(_lazyIsByRefLikeAttribute);
builder.AddIfNotNull(_lazyNullableAttribute);
builder.AddIfNotNull(_lazyNullableContextAttribute);
builder.AddIfNotNull(_lazyNullablePublicOnlyAttribute);
builder.AddIfNotNull(_lazyNativeIntegerAttribute);
return builder.ToImmutableAndFree();
}
public sealed override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context)
{
if (!context.IsRefAssembly)
{
return getFiles(ref _lazyFiles);
}
return getFiles(ref _lazyFilesWithoutManifestResources);
ImmutableArray<Cci.IFileReference> getFiles(ref ImmutableArray<Cci.IFileReference> lazyFiles)
{
if (lazyFiles.IsDefault)
{
var builder = ArrayBuilder<Cci.IFileReference>.GetInstance();
try
{
var modules = _sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
builder.Add((Cci.IFileReference)Translate(modules[i], context.Diagnostics));
}
if (!context.IsRefAssembly)
{
// resources are not emitted into ref assemblies
foreach (ResourceDescription resource in ManifestResources)
{
if (!resource.IsEmbedded)
{
builder.Add(resource);
}
}
}
// Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, builder.ToImmutable()) && lazyFiles.Length > 0)
{
if (!CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm))
{
context.Diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton));
}
}
}
finally
{
builder.Free();
}
}
return lazyFiles;
}
}
protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics)
{
var modules = _sourceAssembly.Modules;
int count = modules.Length;
for (int i = 1; i < count; i++)
{
var file = (Cci.IFileReference)Translate(modules[i], diagnostics);
try
{
foreach (EmbeddedResource resource in ((Symbols.Metadata.PE.PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow())
{
builder.Add(new Cci.ManagedResource(
resource.Name,
(resource.Attributes & ManifestResourceAttributes.Public) != 0,
null,
file,
resource.Offset));
}
}
catch (BadImageFormatException)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton);
}
}
}
public override string Name => _metadataName;
public AssemblyIdentity Identity => _sourceAssembly.Identity;
public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern;
internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute()
{
// _lazyEmbeddedAttribute should have been created before calling this method.
return new SynthesizedAttributeData(
_lazyEmbeddedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNullableAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableAttribute(member, arguments);
}
internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableContextAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullableContextAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableContextAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullablePublicOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullablePublicOnlyAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullablePublicOnlyAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNativeIntegerAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNativeIntegerAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNativeIntegerAttribute(member, arguments);
}
protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
if ((object)_lazyIsReadOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsReadOnlyAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsReadOnlyAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
if ((object)_lazyIsUnmanagedAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsUnmanagedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsUnmanagedAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
if ((object)_lazyIsByRefLikeAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsByRefLikeAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsByRefLikeAttribute();
}
private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics)
{
EmbeddableAttributes needsAttributes = GetNeedsGeneratedAttributes();
if (ShouldEmitNullablePublicOnlyAttribute() &&
Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None))
{
needsAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute;
}
else if (needsAttributes == 0)
{
return;
}
var createParameterlessEmbeddedAttributeSymbol = new Func<string, NamespaceSymbol, BindingDiagnosticBag, SynthesizedEmbeddedAttributeSymbol>(CreateParameterlessEmbeddedAttributeSymbol);
CreateAttributeIfNeeded(
ref _lazyEmbeddedAttribute,
diagnostics,
AttributeDescription.CodeAnalysisEmbeddedAttribute,
createParameterlessEmbeddedAttributeSymbol);
if ((needsAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsReadOnlyAttribute,
diagnostics,
AttributeDescription.IsReadOnlyAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsByRefLikeAttribute,
diagnostics,
AttributeDescription.IsByRefLikeAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsUnmanagedAttribute,
diagnostics,
AttributeDescription.IsUnmanagedAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableAttribute,
diagnostics,
AttributeDescription.NullableAttribute,
CreateNullableAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableContextAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableContextAttribute,
diagnostics,
AttributeDescription.NullableContextAttribute,
CreateNullableContextAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullablePublicOnlyAttribute,
diagnostics,
AttributeDescription.NullablePublicOnlyAttribute,
CreateNullablePublicOnlyAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNativeIntegerAttribute,
diagnostics,
AttributeDescription.NativeIntegerAttribute,
CreateNativeIntegerAttributeSymbol);
}
}
private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedAttributeSymbol(
name,
containingNamespace,
SourceModule,
baseType: GetWellKnownType(WellKnownType.System_Attribute, diagnostics));
private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableContextAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNativeIntegerAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private void CreateAttributeIfNeeded<T>(
ref T symbol,
BindingDiagnosticBag diagnostics,
AttributeDescription description,
Func<string, NamespaceSymbol, BindingDiagnosticBag, T> factory)
where T : SynthesizedEmbeddedAttributeSymbolBase
{
if (symbol is null)
{
AddDiagnosticsForExistingAttribute(description, diagnostics);
var containingNamespace = GetOrSynthesizeNamespace(description.Namespace);
symbol = factory(description.Name, containingNamespace, diagnostics);
Debug.Assert(symbol.Constructors.Length == description.Signatures.Length);
if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default)
{
EnsureAttributeUsageAttributeMembersAvailable(diagnostics);
}
AddSynthesizedDefinition(containingNamespace, symbol);
}
}
private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics)
{
var attributeMetadataName = MetadataTypeName.FromFullName(description.FullName);
var userDefinedAttribute = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref attributeMetadataName);
Debug.Assert((object)userDefinedAttribute.ContainingModule == _sourceAssembly.SourceModule);
if (!(userDefinedAttribute is MissingMetadataTypeSymbol))
{
diagnostics.Add(ErrorCode.ERR_TypeReserved, userDefinedAttribute.Locations[0], description.FullName);
}
}
private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName)
{
var result = SourceModule.GlobalNamespace;
foreach (var partName in namespaceFullName.Split('.'))
{
var subnamespace = (NamespaceSymbol)result.GetMembers(partName).FirstOrDefault(m => m.Kind == SymbolKind.Namespace);
if (subnamespace == null)
{
subnamespace = new SynthesizedNamespaceSymbol(result, partName);
AddSynthesizedDefinition(result, subnamespace);
}
result = subnamespace;
}
return result;
}
private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetSpecialType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics)
{
var compilation = _sourceAssembly.DeclaringCompilation;
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__ctor, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__Inherited, diagnostics, Location.None);
}
}
#nullable enable
internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase
{
public PEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray<NamedTypeSymbol>.Empty)
{
}
public override EmitBaseline? PreviousGeneration => null;
public override SymbolChanges? EncSymbolChanges => null;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Symbols;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.Emit
{
internal abstract class PEAssemblyBuilderBase : PEModuleBuilder, Cci.IAssemblyReference
{
private readonly SourceAssemblySymbol _sourceAssembly;
/// <summary>
/// Additional types injected by the Expression Evaluator.
/// </summary>
private readonly ImmutableArray<NamedTypeSymbol> _additionalTypes;
private ImmutableArray<Cci.IFileReference> _lazyFiles;
/// <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary>
private ImmutableArray<Cci.IFileReference> _lazyFilesWithoutManifestResources;
private SynthesizedEmbeddedAttributeSymbol _lazyEmbeddedAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsReadOnlyAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsByRefLikeAttribute;
private SynthesizedEmbeddedAttributeSymbol _lazyIsUnmanagedAttribute;
private SynthesizedEmbeddedNullableAttributeSymbol _lazyNullableAttribute;
private SynthesizedEmbeddedNullableContextAttributeSymbol _lazyNullableContextAttribute;
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol _lazyNullablePublicOnlyAttribute;
private SynthesizedEmbeddedNativeIntegerAttributeSymbol _lazyNativeIntegerAttribute;
/// <summary>
/// The behavior of the C# command-line compiler is as follows:
/// 1) If the /out switch is specified, then the explicit assembly name is used.
/// 2) Otherwise,
/// a) if the assembly is executable, then the assembly name is derived from
/// the name of the file containing the entrypoint;
/// b) otherwise, the assembly name is derived from the name of the first input
/// file.
///
/// Since we don't know which method is the entrypoint until well after the
/// SourceAssemblySymbol is created, in case 2a, its name will not reflect the
/// name of the file containing the entrypoint. We leave it to our caller to
/// provide that name explicitly.
/// </summary>
/// <remarks>
/// In cases 1 and 2b, we expect (metadataName == sourceAssembly.MetadataName).
/// </remarks>
private readonly string _metadataName;
public PEAssemblyBuilderBase(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources,
ImmutableArray<NamedTypeSymbol> additionalTypes)
: base((SourceModuleSymbol)sourceAssembly.Modules[0], emitOptions, outputKind, serializationProperties, manifestResources)
{
Debug.Assert(sourceAssembly is object);
_sourceAssembly = sourceAssembly;
_additionalTypes = additionalTypes.NullToEmpty();
_metadataName = (emitOptions.OutputNameOverride == null) ? sourceAssembly.MetadataName : FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension: null);
AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, this);
}
public sealed override ISourceAssemblySymbolInternal SourceAssemblyOpt
=> _sourceAssembly;
public sealed override ImmutableArray<NamedTypeSymbol> GetAdditionalTopLevelTypes()
=> _additionalTypes;
internal sealed override ImmutableArray<NamedTypeSymbol> GetEmbeddedTypes(BindingDiagnosticBag diagnostics)
{
var builder = ArrayBuilder<NamedTypeSymbol>.GetInstance();
CreateEmbeddedAttributesIfNeeded(diagnostics);
builder.AddIfNotNull(_lazyEmbeddedAttribute);
builder.AddIfNotNull(_lazyIsReadOnlyAttribute);
builder.AddIfNotNull(_lazyIsUnmanagedAttribute);
builder.AddIfNotNull(_lazyIsByRefLikeAttribute);
builder.AddIfNotNull(_lazyNullableAttribute);
builder.AddIfNotNull(_lazyNullableContextAttribute);
builder.AddIfNotNull(_lazyNullablePublicOnlyAttribute);
builder.AddIfNotNull(_lazyNativeIntegerAttribute);
return builder.ToImmutableAndFree();
}
public sealed override IEnumerable<Cci.IFileReference> GetFiles(EmitContext context)
{
if (!context.IsRefAssembly)
{
return getFiles(ref _lazyFiles);
}
return getFiles(ref _lazyFilesWithoutManifestResources);
ImmutableArray<Cci.IFileReference> getFiles(ref ImmutableArray<Cci.IFileReference> lazyFiles)
{
if (lazyFiles.IsDefault)
{
var builder = ArrayBuilder<Cci.IFileReference>.GetInstance();
try
{
var modules = _sourceAssembly.Modules;
for (int i = 1; i < modules.Length; i++)
{
builder.Add((Cci.IFileReference)Translate(modules[i], context.Diagnostics));
}
if (!context.IsRefAssembly)
{
// resources are not emitted into ref assemblies
foreach (ResourceDescription resource in ManifestResources)
{
if (!resource.IsEmbedded)
{
builder.Add(resource);
}
}
}
// Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
if (ImmutableInterlocked.InterlockedInitialize(ref lazyFiles, builder.ToImmutable()) && lazyFiles.Length > 0)
{
if (!CryptographicHashProvider.IsSupportedAlgorithm(_sourceAssembly.HashAlgorithm))
{
context.Diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_CryptoHashFailed), NoLocation.Singleton));
}
}
}
finally
{
builder.Free();
}
}
return lazyFiles;
}
}
protected override void AddEmbeddedResourcesFromAddedModules(ArrayBuilder<Cci.ManagedResource> builder, DiagnosticBag diagnostics)
{
var modules = _sourceAssembly.Modules;
int count = modules.Length;
for (int i = 1; i < count; i++)
{
var file = (Cci.IFileReference)Translate(modules[i], diagnostics);
try
{
foreach (EmbeddedResource resource in ((Symbols.Metadata.PE.PEModuleSymbol)modules[i]).Module.GetEmbeddedResourcesOrThrow())
{
builder.Add(new Cci.ManagedResource(
resource.Name,
(resource.Attributes & ManifestResourceAttributes.Public) != 0,
null,
file,
resource.Offset));
}
}
catch (BadImageFormatException)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, modules[i]), NoLocation.Singleton);
}
}
}
public override string Name => _metadataName;
public AssemblyIdentity Identity => _sourceAssembly.Identity;
public Version AssemblyVersionPattern => _sourceAssembly.AssemblyVersionPattern;
internal override SynthesizedAttributeData SynthesizeEmbeddedAttribute()
{
// _lazyEmbeddedAttribute should have been created before calling this method.
return new SynthesizedAttributeData(
_lazyEmbeddedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
internal override SynthesizedAttributeData SynthesizeNullableAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NullableAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNullableAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableAttribute(member, arguments);
}
internal override SynthesizedAttributeData SynthesizeNullableContextAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullableContextAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullableContextAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullableContextAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNullablePublicOnlyAttribute(ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNullablePublicOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyNullablePublicOnlyAttribute.Constructors[0],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNullablePublicOnlyAttribute(arguments);
}
internal override SynthesizedAttributeData SynthesizeNativeIntegerAttribute(WellKnownMember member, ImmutableArray<TypedConstant> arguments)
{
if ((object)_lazyNativeIntegerAttribute != null)
{
var constructorIndex = (member == WellKnownMember.System_Runtime_CompilerServices_NativeIntegerAttribute__ctorTransformFlags) ? 1 : 0;
return new SynthesizedAttributeData(
_lazyNativeIntegerAttribute.Constructors[constructorIndex],
arguments,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.SynthesizeNativeIntegerAttribute(member, arguments);
}
protected override SynthesizedAttributeData TrySynthesizeIsReadOnlyAttribute()
{
if ((object)_lazyIsReadOnlyAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsReadOnlyAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsReadOnlyAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsUnmanagedAttribute()
{
if ((object)_lazyIsUnmanagedAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsUnmanagedAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsUnmanagedAttribute();
}
protected override SynthesizedAttributeData TrySynthesizeIsByRefLikeAttribute()
{
if ((object)_lazyIsByRefLikeAttribute != null)
{
return new SynthesizedAttributeData(
_lazyIsByRefLikeAttribute.Constructors[0],
ImmutableArray<TypedConstant>.Empty,
ImmutableArray<KeyValuePair<string, TypedConstant>>.Empty);
}
return base.TrySynthesizeIsByRefLikeAttribute();
}
private void CreateEmbeddedAttributesIfNeeded(BindingDiagnosticBag diagnostics)
{
EmbeddableAttributes needsAttributes = GetNeedsGeneratedAttributes();
if (ShouldEmitNullablePublicOnlyAttribute() &&
Compilation.CheckIfAttributeShouldBeEmbedded(EmbeddableAttributes.NullablePublicOnlyAttribute, diagnostics, Location.None))
{
needsAttributes |= EmbeddableAttributes.NullablePublicOnlyAttribute;
}
else if (needsAttributes == 0)
{
return;
}
var createParameterlessEmbeddedAttributeSymbol = new Func<string, NamespaceSymbol, BindingDiagnosticBag, SynthesizedEmbeddedAttributeSymbol>(CreateParameterlessEmbeddedAttributeSymbol);
CreateAttributeIfNeeded(
ref _lazyEmbeddedAttribute,
diagnostics,
AttributeDescription.CodeAnalysisEmbeddedAttribute,
createParameterlessEmbeddedAttributeSymbol);
if ((needsAttributes & EmbeddableAttributes.IsReadOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsReadOnlyAttribute,
diagnostics,
AttributeDescription.IsReadOnlyAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsByRefLikeAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsByRefLikeAttribute,
diagnostics,
AttributeDescription.IsByRefLikeAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.IsUnmanagedAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyIsUnmanagedAttribute,
diagnostics,
AttributeDescription.IsUnmanagedAttribute,
createParameterlessEmbeddedAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableAttribute,
diagnostics,
AttributeDescription.NullableAttribute,
CreateNullableAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullableContextAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullableContextAttribute,
diagnostics,
AttributeDescription.NullableContextAttribute,
CreateNullableContextAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NullablePublicOnlyAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNullablePublicOnlyAttribute,
diagnostics,
AttributeDescription.NullablePublicOnlyAttribute,
CreateNullablePublicOnlyAttributeSymbol);
}
if ((needsAttributes & EmbeddableAttributes.NativeIntegerAttribute) != 0)
{
CreateAttributeIfNeeded(
ref _lazyNativeIntegerAttribute,
diagnostics,
AttributeDescription.NativeIntegerAttribute,
CreateNativeIntegerAttributeSymbol);
}
}
private SynthesizedEmbeddedAttributeSymbol CreateParameterlessEmbeddedAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedAttributeSymbol(
name,
containingNamespace,
SourceModule,
baseType: GetWellKnownType(WellKnownType.System_Attribute, diagnostics));
private SynthesizedEmbeddedNullableAttributeSymbol CreateNullableAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullableContextAttributeSymbol CreateNullableContextAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullableContextAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Byte, diagnostics));
private SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol CreateNullablePublicOnlyAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNullablePublicOnlyAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private SynthesizedEmbeddedNativeIntegerAttributeSymbol CreateNativeIntegerAttributeSymbol(string name, NamespaceSymbol containingNamespace, BindingDiagnosticBag diagnostics)
=> new SynthesizedEmbeddedNativeIntegerAttributeSymbol(
name,
containingNamespace,
SourceModule,
GetWellKnownType(WellKnownType.System_Attribute, diagnostics),
GetSpecialType(SpecialType.System_Boolean, diagnostics));
private void CreateAttributeIfNeeded<T>(
ref T symbol,
BindingDiagnosticBag diagnostics,
AttributeDescription description,
Func<string, NamespaceSymbol, BindingDiagnosticBag, T> factory)
where T : SynthesizedEmbeddedAttributeSymbolBase
{
if (symbol is null)
{
AddDiagnosticsForExistingAttribute(description, diagnostics);
var containingNamespace = GetOrSynthesizeNamespace(description.Namespace);
symbol = factory(description.Name, containingNamespace, diagnostics);
Debug.Assert(symbol.Constructors.Length == description.Signatures.Length);
if (symbol.GetAttributeUsageInfo() != AttributeUsageInfo.Default)
{
EnsureAttributeUsageAttributeMembersAvailable(diagnostics);
}
AddSynthesizedDefinition(containingNamespace, symbol);
}
}
private void AddDiagnosticsForExistingAttribute(AttributeDescription description, BindingDiagnosticBag diagnostics)
{
var attributeMetadataName = MetadataTypeName.FromFullName(description.FullName);
var userDefinedAttribute = _sourceAssembly.SourceModule.LookupTopLevelMetadataType(ref attributeMetadataName);
Debug.Assert((object)userDefinedAttribute.ContainingModule == _sourceAssembly.SourceModule);
if (!(userDefinedAttribute is MissingMetadataTypeSymbol))
{
diagnostics.Add(ErrorCode.ERR_TypeReserved, userDefinedAttribute.Locations[0], description.FullName);
}
}
private NamespaceSymbol GetOrSynthesizeNamespace(string namespaceFullName)
{
var result = SourceModule.GlobalNamespace;
foreach (var partName in namespaceFullName.Split('.'))
{
var subnamespace = (NamespaceSymbol)result.GetMembers(partName).FirstOrDefault(m => m.Kind == SymbolKind.Namespace);
if (subnamespace == null)
{
subnamespace = new SynthesizedNamespaceSymbol(result, partName);
AddSynthesizedDefinition(result, subnamespace);
}
result = subnamespace;
}
return result;
}
private NamedTypeSymbol GetWellKnownType(WellKnownType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetWellKnownType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private NamedTypeSymbol GetSpecialType(SpecialType type, BindingDiagnosticBag diagnostics)
{
var result = _sourceAssembly.DeclaringCompilation.GetSpecialType(type);
Binder.ReportUseSite(result, diagnostics, Location.None);
return result;
}
private void EnsureAttributeUsageAttributeMembersAvailable(BindingDiagnosticBag diagnostics)
{
var compilation = _sourceAssembly.DeclaringCompilation;
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__ctor, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__AllowMultiple, diagnostics, Location.None);
Binder.GetWellKnownTypeMember(compilation, WellKnownMember.System_AttributeUsageAttribute__Inherited, diagnostics, Location.None);
}
}
#nullable enable
internal sealed class PEAssemblyBuilder : PEAssemblyBuilderBase
{
public PEAssemblyBuilder(
SourceAssemblySymbol sourceAssembly,
EmitOptions emitOptions,
OutputKind outputKind,
Cci.ModulePropertiesForSerialization serializationProperties,
IEnumerable<ResourceDescription> manifestResources)
: base(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, ImmutableArray<NamedTypeSymbol>.Empty)
{
}
public override EmitBaseline? PreviousGeneration => null;
public override SymbolChanges? EncSymbolChanges => null;
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/Shared/CoreClrShim.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using System;
using System.Reflection;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Shim for APIs available only on CoreCLR.
/// </summary>
internal static class CoreClrShim
{
internal static bool IsRunningOnCoreClr => AssemblyLoadContext.Type != null;
internal static class AssemblyLoadContext
{
internal static readonly Type Type = ReflectionUtilities.TryGetType(
"System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
}
internal static class AppContext
{
internal static readonly Type Type = ReflectionUtilities.TryGetType(
"System.AppContext, System.AppContext, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
// only available in netstandard 1.6+
internal static readonly Func<string, object> GetData =
Type.GetTypeInfo().GetDeclaredMethod("GetData")?.CreateDelegate<Func<string, object>>();
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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;
using System;
using System.Reflection;
namespace Microsoft.CodeAnalysis
{
/// <summary>
/// Shim for APIs available only on CoreCLR.
/// </summary>
internal static class CoreClrShim
{
internal static bool IsRunningOnCoreClr => AssemblyLoadContext.Type != null;
internal static class AssemblyLoadContext
{
internal static readonly Type Type = ReflectionUtilities.TryGetType(
"System.Runtime.Loader.AssemblyLoadContext, System.Runtime.Loader, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
}
internal static class AppContext
{
internal static readonly Type Type = ReflectionUtilities.TryGetType(
"System.AppContext, System.AppContext, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
// only available in netstandard 1.6+
internal static readonly Func<string, object> GetData =
Type.GetTypeInfo().GetDeclaredMethod("GetData")?.CreateDelegate<Func<string, object>>();
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/CSharp/Portable/ConvertToInterpolatedString/CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertToInterpolatedString;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.ConvertToInterpolatedString
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString), Shared]
internal partial class CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider :
AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider<InvocationExpressionSyntax, ExpressionSyntax, ArgumentSyntax, LiteralExpressionSyntax, ArgumentListSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider()
{
}
protected override SyntaxNode GetInterpolatedString(string text)
=> SyntaxFactory.ParseExpression("$" + text) as InterpolatedStringExpressionSyntax;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System.Composition;
using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeRefactorings;
using Microsoft.CodeAnalysis.ConvertToInterpolatedString;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Microsoft.CodeAnalysis.CSharp.ConvertToInterpolatedString
{
[ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = PredefinedCodeRefactoringProviderNames.ConvertPlaceholderToInterpolatedString), Shared]
internal partial class CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider :
AbstractConvertPlaceholderToInterpolatedStringRefactoringProvider<InvocationExpressionSyntax, ExpressionSyntax, ArgumentSyntax, LiteralExpressionSyntax, ArgumentListSyntax>
{
[ImportingConstructor]
[SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")]
public CSharpConvertPlaceholderToInterpolatedStringRefactoringProvider()
{
}
protected override SyntaxNode GetInterpolatedString(string text)
=> SyntaxFactory.ParseExpression("$" + text) as InterpolatedStringExpressionSyntax;
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/CSharp/Test/IOperation/IOperation/IOperationTests_IDeclarationExpression.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDeclarationExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeclarationFlow_01()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
M2(b ? out var i1 : out var i2);
}/*</bind>*/
public void M2(out int i)
{
i = 0;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'out'
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 16),
// CS1003: Syntax error, ':' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(":", "out").WithLocation(6, 16),
// CS1525: Invalid expression term 'out'
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 16),
// CS1003: Syntax error, ',' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 16),
// CS1003: Syntax error, ',' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(6, 27),
// CS1003: Syntax error, ',' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 29)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [var i1] [var i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Value:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Value:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2(b ? out ... ut var i2);')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(b ? out ... out var i2)')
Children(3):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'b ? ')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var) (Syntax: 'var i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'i1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var) (Syntax: 'var i2')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'i2')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class IOperationTests_IDeclarationExpression : SemanticModelTestBase
{
[CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)]
[Fact]
public void DeclarationFlow_01()
{
string source = @"
class C
{
void M(bool b)
/*<bind>*/{
M2(b ? out var i1 : out var i2);
}/*</bind>*/
public void M2(out int i)
{
i = 0;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1525: Invalid expression term 'out'
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 16),
// CS1003: Syntax error, ':' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(":", "out").WithLocation(6, 16),
// CS1525: Invalid expression term 'out'
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "out").WithArguments("out").WithLocation(6, 16),
// CS1003: Syntax error, ',' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 16),
// CS1003: Syntax error, ',' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, ":").WithArguments(",", ":").WithLocation(6, 27),
// CS1003: Syntax error, ',' expected
// M2(b ? out var i1 : out var i2);
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(6, 29)
};
string expectedFlowGraph = @"
Block[B0] - Entry
Statements (0)
Next (Regular) Block[B1]
Entering: {R1}
.locals {R1}
{
Locals: [var i1] [var i2]
CaptureIds: [0]
Block[B1] - Block
Predecessors: [B0]
Statements (0)
Jump if False (Regular) to Block[B3]
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Boolean) (Syntax: 'b')
Next (Regular) Block[B2]
Block[B2] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Value:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B4]
Block[B3] - Block
Predecessors: [B1]
Statements (1)
IFlowCaptureOperation: 0 (OperationKind.FlowCapture, Type: null, IsInvalid, IsImplicit) (Syntax: '')
Value:
IInvalidOperation (OperationKind.Invalid, Type: null, IsInvalid) (Syntax: '')
Children(0)
Next (Regular) Block[B4]
Block[B4] - Block
Predecessors: [B2] [B3]
Statements (1)
IExpressionStatementOperation (OperationKind.ExpressionStatement, Type: null, IsInvalid) (Syntax: 'M2(b ? out ... ut var i2);')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Void, IsInvalid) (Syntax: 'M2(b ? out ... out var i2)')
Children(3):
IFlowCaptureReferenceOperation: 0 (OperationKind.FlowCaptureReference, Type: ?, IsInvalid, IsImplicit) (Syntax: 'b ? ')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var) (Syntax: 'var i1')
ILocalReferenceOperation: i1 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'i1')
IDeclarationExpressionOperation (OperationKind.DeclarationExpression, Type: var) (Syntax: 'var i2')
ILocalReferenceOperation: i2 (IsDeclaration: True) (OperationKind.LocalReference, Type: var) (Syntax: 'i2')
Next (Regular) Block[B5]
Leaving: {R1}
}
Block[B5] - Exit
Predecessors: [B4]
Statements (0)
";
VerifyFlowGraphAndDiagnosticsForTest<BlockSyntax>(source, expectedFlowGraph, expectedDiagnostics);
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/Core/Formatting/Engine/AbstractFormatEngine.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
// TODO : two alternative design possible for formatting engine
//
// 1. use AAL (TPL Dataflow) in .NET 4.5 to run things concurrently in sequential order
// * this has a problem of the new TPL lib being not released yet and possibility of not using all cores.
//
// 2. create dependency graph between operations, and format them in topological order and
// run chunks that don't have dependency in parallel (kirill's idea)
// * this requires defining dependencies on each operations. can't use dependency between tokens since
// that would create too big graph. key for this approach is how to reduce size of graph.
internal abstract partial class AbstractFormatEngine
{
private readonly ChainedFormattingRules _formattingRules;
private readonly SyntaxNode _commonRoot;
private readonly SyntaxToken _token1;
private readonly SyntaxToken _token2;
protected readonly TextSpan SpanToFormat;
internal readonly AnalyzerConfigOptions Options;
internal readonly TreeData TreeData;
public AbstractFormatEngine(
TreeData treeData,
AnalyzerConfigOptions options,
IEnumerable<AbstractFormattingRule> formattingRules,
SyntaxToken token1,
SyntaxToken token2)
: this(
treeData,
options,
new ChainedFormattingRules(formattingRules, options),
token1,
token2)
{
}
internal AbstractFormatEngine(
TreeData treeData,
AnalyzerConfigOptions options,
ChainedFormattingRules formattingRules,
SyntaxToken token1,
SyntaxToken token2)
{
Contract.ThrowIfNull(options);
Contract.ThrowIfNull(treeData);
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfTrue(treeData.Root.IsInvalidTokenRange(token1, token2));
this.Options = options;
this.TreeData = treeData;
_formattingRules = formattingRules;
_token1 = token1;
_token2 = token2;
// get span and common root
this.SpanToFormat = GetSpanToFormat();
_commonRoot = token1.GetCommonRoot(token2) ?? throw ExceptionUtilities.Unreachable;
}
internal abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract AbstractTriviaDataFactory CreateTriviaFactory();
protected abstract AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream);
public AbstractFormattingResult Format(CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_Format, FormatSummary, cancellationToken))
{
// setup environment
var nodeOperations = CreateNodeOperations(cancellationToken);
var tokenStream = new TokenStream(this.TreeData, this.Options, this.SpanToFormat, CreateTriviaFactory());
var tokenOperation = CreateTokenOperation(tokenStream, cancellationToken);
// initialize context
var context = CreateFormattingContext(tokenStream, cancellationToken);
// start anchor task that will be used later
cancellationToken.ThrowIfCancellationRequested();
var anchorContext = nodeOperations.AnchorIndentationOperations.Do(context.AddAnchorIndentationOperation);
BuildContext(context, nodeOperations, cancellationToken);
ApplyBeginningOfTreeTriviaOperation(context, cancellationToken);
ApplyTokenOperations(context, nodeOperations,
tokenOperation, cancellationToken);
ApplyTriviaOperations(context, cancellationToken);
ApplyEndOfTreeTriviaOperation(context, cancellationToken);
return CreateFormattingResult(tokenStream);
}
}
protected virtual FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken)
{
// initialize context
var context = new FormattingContext(this, tokenStream);
context.Initialize(_formattingRules, _token1, _token2, cancellationToken);
return context;
}
protected virtual NodeOperations CreateNodeOperations(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// iterating tree is very expensive. do it once and cache it to list
SegmentedList<SyntaxNode> nodeIterator;
using (Logger.LogBlock(FunctionId.Formatting_IterateNodes, cancellationToken))
{
const int magicLengthToNodesRatio = 5;
var result = new SegmentedList<SyntaxNode>(Math.Max(this.SpanToFormat.Length / magicLengthToNodesRatio, 4));
foreach (var node in _commonRoot.DescendantNodesAndSelf(this.SpanToFormat))
{
cancellationToken.ThrowIfCancellationRequested();
result.Add(node);
}
nodeIterator = result;
}
// iterate through each operation using index to not create any unnecessary object
cancellationToken.ThrowIfCancellationRequested();
List<IndentBlockOperation> indentBlockOperation;
using (Logger.LogBlock(FunctionId.Formatting_CollectIndentBlock, cancellationToken))
{
indentBlockOperation = AddOperations<IndentBlockOperation>(nodeIterator, (l, n) => _formattingRules.AddIndentBlockOperations(l, n), cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
List<SuppressOperation> suppressOperation;
using (Logger.LogBlock(FunctionId.Formatting_CollectSuppressOperation, cancellationToken))
{
suppressOperation = AddOperations<SuppressOperation>(nodeIterator, (l, n) => _formattingRules.AddSuppressOperations(l, n), cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
List<AlignTokensOperation> alignmentOperation;
using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken))
{
var operations = AddOperations<AlignTokensOperation>(nodeIterator, (l, n) => _formattingRules.AddAlignTokensOperations(l, n), cancellationToken);
// make sure we order align operation from left to right
operations.Sort((o1, o2) => o1.BaseToken.Span.CompareTo(o2.BaseToken.Span));
alignmentOperation = operations;
}
cancellationToken.ThrowIfCancellationRequested();
List<AnchorIndentationOperation> anchorIndentationOperations;
using (Logger.LogBlock(FunctionId.Formatting_CollectAnchorOperation, cancellationToken))
{
anchorIndentationOperations = AddOperations<AnchorIndentationOperation>(nodeIterator, (l, n) => _formattingRules.AddAnchorIndentationOperations(l, n), cancellationToken);
}
return new NodeOperations(indentBlockOperation, suppressOperation, anchorIndentationOperations, alignmentOperation);
}
private static List<T> AddOperations<T>(SegmentedList<SyntaxNode> nodes, Action<List<T>, SyntaxNode> addOperations, CancellationToken cancellationToken)
{
var operations = new List<T>();
var list = new List<T>();
foreach (var n in nodes)
{
cancellationToken.ThrowIfCancellationRequested();
addOperations(list, n);
list.RemoveAll(item => item == null);
operations.AddRange(list);
list.Clear();
}
return operations;
}
private SegmentedArray<TokenPairWithOperations> CreateTokenOperation(
TokenStream tokenStream,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
using (Logger.LogBlock(FunctionId.Formatting_CollectTokenOperation, cancellationToken))
{
// pre-allocate list once. this is cheaper than re-adjusting list as items are added.
var list = new SegmentedArray<TokenPairWithOperations>(tokenStream.TokenCount - 1);
foreach (var (index, currentToken, nextToken) in tokenStream.TokenIterator)
{
cancellationToken.ThrowIfCancellationRequested();
var spaceOperation = _formattingRules.GetAdjustSpacesOperation(currentToken, nextToken);
var lineOperation = _formattingRules.GetAdjustNewLinesOperation(currentToken, nextToken);
list[index] = new TokenPairWithOperations(tokenStream, index, spaceOperation, lineOperation);
}
return list;
}
}
private void ApplyTokenOperations(
FormattingContext context,
NodeOperations nodeOperations,
SegmentedArray<TokenPairWithOperations> tokenOperations,
CancellationToken cancellationToken)
{
var applier = new OperationApplier(context, _formattingRules);
ApplySpaceAndWrappingOperations(context, tokenOperations, applier, cancellationToken);
ApplyAnchorOperations(context, tokenOperations, applier, cancellationToken);
ApplySpecialOperations(context, nodeOperations, applier, cancellationToken);
}
private void ApplyBeginningOfTreeTriviaOperation(
FormattingContext context, CancellationToken cancellationToken)
{
if (!context.TokenStream.FormatBeginningOfTree)
{
return;
}
// remove all leading indentation
var triviaInfo = context.TokenStream.GetTriviaDataAtBeginningOfTree().WithIndentation(0, context, _formattingRules, cancellationToken);
triviaInfo.Format(context, _formattingRules, BeginningOfTreeTriviaInfoApplier, cancellationToken);
return;
// local functions
static void BeginningOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info)
=> ts.ApplyBeginningOfTreeChange(info);
}
private void ApplyEndOfTreeTriviaOperation(
FormattingContext context, CancellationToken cancellationToken)
{
if (!context.TokenStream.FormatEndOfTree)
{
return;
}
if (context.IsFormattingDisabled(new TextSpan(context.TokenStream.LastTokenInStream.Token.SpanStart, 0)))
{
// Formatting is suppressed in the document, and not restored before the end
return;
}
// remove all trailing indentation
var triviaInfo = context.TokenStream.GetTriviaDataAtEndOfTree().WithIndentation(0, context, _formattingRules, cancellationToken);
triviaInfo.Format(context, _formattingRules, EndOfTreeTriviaInfoApplier, cancellationToken);
return;
// local functions
static void EndOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info)
=> ts.ApplyEndOfTreeChange(info);
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures = false)]
private void ApplyTriviaOperations(FormattingContext context, CancellationToken cancellationToken)
{
for (var i = 0; i < context.TokenStream.TokenCount - 1; i++)
{
cancellationToken.ThrowIfCancellationRequested();
TriviaFormatter(i, context, _formattingRules, cancellationToken);
}
return;
// local functions
static void RegularApplier(int tokenPairIndex, TokenStream ts, TriviaData info)
=> ts.ApplyChange(tokenPairIndex, info);
static void TriviaFormatter(int tokenPairIndex, FormattingContext ctx, ChainedFormattingRules formattingRules, CancellationToken ct)
{
if (ctx.IsFormattingDisabled(tokenPairIndex))
{
return;
}
var triviaInfo = ctx.TokenStream.GetTriviaData(tokenPairIndex);
triviaInfo.Format(
ctx,
formattingRules,
(tokenPairIndex1, ts, info) => RegularApplier(tokenPairIndex1, ts, info),
ct,
tokenPairIndex);
}
}
private TextSpan GetSpanToFormat()
{
var startPosition = this.TreeData.IsFirstToken(_token1) ? this.TreeData.StartPosition : _token1.SpanStart;
var endPosition = this.TreeData.IsLastToken(_token2) ? this.TreeData.EndPosition : _token2.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private static void ApplySpecialOperations(
FormattingContext context, NodeOperations nodeOperationsCollector, OperationApplier applier, CancellationToken cancellationToken)
{
// apply alignment operation
using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
// TODO : figure out a way to run alignment operations in parallel. probably find
// unions and run each chunk in separate tasks
var previousChangesMap = new Dictionary<SyntaxToken, int>();
var alignmentOperations = nodeOperationsCollector.AlignmentOperation;
alignmentOperations.Do(operation =>
{
cancellationToken.ThrowIfCancellationRequested();
applier.ApplyAlignment(operation, previousChangesMap, cancellationToken);
});
// go through all relative indent block operation, and see whether it is affected by previous operations
context.GetAllRelativeIndentBlockOperations().Do(o =>
{
cancellationToken.ThrowIfCancellationRequested();
applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken);
});
}
}
private static void ApplyAnchorOperations(
FormattingContext context,
SegmentedArray<TokenPairWithOperations> tokenOperations,
OperationApplier applier,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_ApplyAnchorOperation, cancellationToken))
{
// TODO: find out a way to apply anchor operation concurrently if possible
var previousChangesMap = new Dictionary<SyntaxToken, int>();
foreach (var p in tokenOperations)
{
cancellationToken.ThrowIfCancellationRequested();
if (!AnchorOperationCandidate(p))
{
continue;
}
var pairIndex = p.PairIndex;
applier.ApplyAnchorIndentation(pairIndex, previousChangesMap, cancellationToken);
}
// go through all relative indent block operation, and see whether it is affected by the anchor operation
context.GetAllRelativeIndentBlockOperations().Do(o =>
{
cancellationToken.ThrowIfCancellationRequested();
applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken);
});
}
}
private static bool AnchorOperationCandidate(TokenPairWithOperations pair)
{
if (pair.LineOperation == null)
{
return pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine;
}
if (pair.LineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
return !pair.TokenStream.TwoTokensOriginallyOnSameLine(pair.Token1, pair.Token2) &&
pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine;
}
return false;
}
private static SyntaxToken FindCorrectBaseTokenOfRelativeIndentBlockOperation(IndentBlockOperation operation, TokenStream tokenStream)
{
if (operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine))
{
return tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken);
}
return operation.BaseToken;
}
private static void ApplySpaceAndWrappingOperations(
FormattingContext context,
SegmentedArray<TokenPairWithOperations> tokenOperations,
OperationApplier applier,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_ApplySpaceAndLine, cancellationToken))
{
// go through each token pairs and apply operations
foreach (var operationPair in tokenOperations)
{
ApplySpaceAndWrappingOperationsBody(context, operationPair, applier, cancellationToken);
}
}
}
private static void ApplySpaceAndWrappingOperationsBody(
FormattingContext context,
TokenPairWithOperations operation,
OperationApplier applier,
CancellationToken cancellationToken)
{
var token1 = operation.Token1;
var token2 = operation.Token2;
// check whether one of tokens is missing (which means syntax error exist around two tokens)
// in error case, we leave code as user wrote
if (token1.IsMissing || token2.IsMissing)
{
return;
}
var triviaInfo = context.TokenStream.GetTriviaData(operation.PairIndex);
var spanBetweenTokens = TextSpan.FromBounds(token1.Span.End, token2.SpanStart);
if (operation.LineOperation != null)
{
if (!context.IsWrappingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic))
{
// TODO : need to revisit later for the case where line and space operations
// are conflicting each other by forcing new lines and removing new lines.
//
// if wrapping operation applied, no need to run any other operation
if (applier.Apply(operation.LineOperation, operation.PairIndex, cancellationToken))
{
return;
}
}
}
if (operation.SpaceOperation != null)
{
if (!context.IsSpacingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic))
{
applier.Apply(operation.SpaceOperation, operation.PairIndex);
}
}
}
private static void BuildContext(
FormattingContext context,
NodeOperations nodeOperations,
CancellationToken cancellationToken)
{
// add scope operation (run each kind sequentially)
using (Logger.LogBlock(FunctionId.Formatting_BuildContext, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
context.AddIndentBlockOperations(nodeOperations.IndentBlockOperation, cancellationToken);
context.AddSuppressOperations(nodeOperations.SuppressOperation, cancellationToken);
}
}
/// <summary>
/// return summary for current formatting work
/// </summary>
private string FormatSummary()
{
return string.Format("({0}) ({1} - {2})",
this.SpanToFormat,
_token1.ToString().Replace("\r\n", "\\r\\n"),
_token2.ToString().Replace("\r\n", "\\r\\n"));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Utilities;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Formatting
{
// TODO : two alternative design possible for formatting engine
//
// 1. use AAL (TPL Dataflow) in .NET 4.5 to run things concurrently in sequential order
// * this has a problem of the new TPL lib being not released yet and possibility of not using all cores.
//
// 2. create dependency graph between operations, and format them in topological order and
// run chunks that don't have dependency in parallel (kirill's idea)
// * this requires defining dependencies on each operations. can't use dependency between tokens since
// that would create too big graph. key for this approach is how to reduce size of graph.
internal abstract partial class AbstractFormatEngine
{
private readonly ChainedFormattingRules _formattingRules;
private readonly SyntaxNode _commonRoot;
private readonly SyntaxToken _token1;
private readonly SyntaxToken _token2;
protected readonly TextSpan SpanToFormat;
internal readonly AnalyzerConfigOptions Options;
internal readonly TreeData TreeData;
public AbstractFormatEngine(
TreeData treeData,
AnalyzerConfigOptions options,
IEnumerable<AbstractFormattingRule> formattingRules,
SyntaxToken token1,
SyntaxToken token2)
: this(
treeData,
options,
new ChainedFormattingRules(formattingRules, options),
token1,
token2)
{
}
internal AbstractFormatEngine(
TreeData treeData,
AnalyzerConfigOptions options,
ChainedFormattingRules formattingRules,
SyntaxToken token1,
SyntaxToken token2)
{
Contract.ThrowIfNull(options);
Contract.ThrowIfNull(treeData);
Contract.ThrowIfNull(formattingRules);
Contract.ThrowIfTrue(treeData.Root.IsInvalidTokenRange(token1, token2));
this.Options = options;
this.TreeData = treeData;
_formattingRules = formattingRules;
_token1 = token1;
_token2 = token2;
// get span and common root
this.SpanToFormat = GetSpanToFormat();
_commonRoot = token1.GetCommonRoot(token2) ?? throw ExceptionUtilities.Unreachable;
}
internal abstract ISyntaxFacts SyntaxFacts { get; }
protected abstract AbstractTriviaDataFactory CreateTriviaFactory();
protected abstract AbstractFormattingResult CreateFormattingResult(TokenStream tokenStream);
public AbstractFormattingResult Format(CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_Format, FormatSummary, cancellationToken))
{
// setup environment
var nodeOperations = CreateNodeOperations(cancellationToken);
var tokenStream = new TokenStream(this.TreeData, this.Options, this.SpanToFormat, CreateTriviaFactory());
var tokenOperation = CreateTokenOperation(tokenStream, cancellationToken);
// initialize context
var context = CreateFormattingContext(tokenStream, cancellationToken);
// start anchor task that will be used later
cancellationToken.ThrowIfCancellationRequested();
var anchorContext = nodeOperations.AnchorIndentationOperations.Do(context.AddAnchorIndentationOperation);
BuildContext(context, nodeOperations, cancellationToken);
ApplyBeginningOfTreeTriviaOperation(context, cancellationToken);
ApplyTokenOperations(context, nodeOperations,
tokenOperation, cancellationToken);
ApplyTriviaOperations(context, cancellationToken);
ApplyEndOfTreeTriviaOperation(context, cancellationToken);
return CreateFormattingResult(tokenStream);
}
}
protected virtual FormattingContext CreateFormattingContext(TokenStream tokenStream, CancellationToken cancellationToken)
{
// initialize context
var context = new FormattingContext(this, tokenStream);
context.Initialize(_formattingRules, _token1, _token2, cancellationToken);
return context;
}
protected virtual NodeOperations CreateNodeOperations(CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
// iterating tree is very expensive. do it once and cache it to list
SegmentedList<SyntaxNode> nodeIterator;
using (Logger.LogBlock(FunctionId.Formatting_IterateNodes, cancellationToken))
{
const int magicLengthToNodesRatio = 5;
var result = new SegmentedList<SyntaxNode>(Math.Max(this.SpanToFormat.Length / magicLengthToNodesRatio, 4));
foreach (var node in _commonRoot.DescendantNodesAndSelf(this.SpanToFormat))
{
cancellationToken.ThrowIfCancellationRequested();
result.Add(node);
}
nodeIterator = result;
}
// iterate through each operation using index to not create any unnecessary object
cancellationToken.ThrowIfCancellationRequested();
List<IndentBlockOperation> indentBlockOperation;
using (Logger.LogBlock(FunctionId.Formatting_CollectIndentBlock, cancellationToken))
{
indentBlockOperation = AddOperations<IndentBlockOperation>(nodeIterator, (l, n) => _formattingRules.AddIndentBlockOperations(l, n), cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
List<SuppressOperation> suppressOperation;
using (Logger.LogBlock(FunctionId.Formatting_CollectSuppressOperation, cancellationToken))
{
suppressOperation = AddOperations<SuppressOperation>(nodeIterator, (l, n) => _formattingRules.AddSuppressOperations(l, n), cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
List<AlignTokensOperation> alignmentOperation;
using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken))
{
var operations = AddOperations<AlignTokensOperation>(nodeIterator, (l, n) => _formattingRules.AddAlignTokensOperations(l, n), cancellationToken);
// make sure we order align operation from left to right
operations.Sort((o1, o2) => o1.BaseToken.Span.CompareTo(o2.BaseToken.Span));
alignmentOperation = operations;
}
cancellationToken.ThrowIfCancellationRequested();
List<AnchorIndentationOperation> anchorIndentationOperations;
using (Logger.LogBlock(FunctionId.Formatting_CollectAnchorOperation, cancellationToken))
{
anchorIndentationOperations = AddOperations<AnchorIndentationOperation>(nodeIterator, (l, n) => _formattingRules.AddAnchorIndentationOperations(l, n), cancellationToken);
}
return new NodeOperations(indentBlockOperation, suppressOperation, anchorIndentationOperations, alignmentOperation);
}
private static List<T> AddOperations<T>(SegmentedList<SyntaxNode> nodes, Action<List<T>, SyntaxNode> addOperations, CancellationToken cancellationToken)
{
var operations = new List<T>();
var list = new List<T>();
foreach (var n in nodes)
{
cancellationToken.ThrowIfCancellationRequested();
addOperations(list, n);
list.RemoveAll(item => item == null);
operations.AddRange(list);
list.Clear();
}
return operations;
}
private SegmentedArray<TokenPairWithOperations> CreateTokenOperation(
TokenStream tokenStream,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
using (Logger.LogBlock(FunctionId.Formatting_CollectTokenOperation, cancellationToken))
{
// pre-allocate list once. this is cheaper than re-adjusting list as items are added.
var list = new SegmentedArray<TokenPairWithOperations>(tokenStream.TokenCount - 1);
foreach (var (index, currentToken, nextToken) in tokenStream.TokenIterator)
{
cancellationToken.ThrowIfCancellationRequested();
var spaceOperation = _formattingRules.GetAdjustSpacesOperation(currentToken, nextToken);
var lineOperation = _formattingRules.GetAdjustNewLinesOperation(currentToken, nextToken);
list[index] = new TokenPairWithOperations(tokenStream, index, spaceOperation, lineOperation);
}
return list;
}
}
private void ApplyTokenOperations(
FormattingContext context,
NodeOperations nodeOperations,
SegmentedArray<TokenPairWithOperations> tokenOperations,
CancellationToken cancellationToken)
{
var applier = new OperationApplier(context, _formattingRules);
ApplySpaceAndWrappingOperations(context, tokenOperations, applier, cancellationToken);
ApplyAnchorOperations(context, tokenOperations, applier, cancellationToken);
ApplySpecialOperations(context, nodeOperations, applier, cancellationToken);
}
private void ApplyBeginningOfTreeTriviaOperation(
FormattingContext context, CancellationToken cancellationToken)
{
if (!context.TokenStream.FormatBeginningOfTree)
{
return;
}
// remove all leading indentation
var triviaInfo = context.TokenStream.GetTriviaDataAtBeginningOfTree().WithIndentation(0, context, _formattingRules, cancellationToken);
triviaInfo.Format(context, _formattingRules, BeginningOfTreeTriviaInfoApplier, cancellationToken);
return;
// local functions
static void BeginningOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info)
=> ts.ApplyBeginningOfTreeChange(info);
}
private void ApplyEndOfTreeTriviaOperation(
FormattingContext context, CancellationToken cancellationToken)
{
if (!context.TokenStream.FormatEndOfTree)
{
return;
}
if (context.IsFormattingDisabled(new TextSpan(context.TokenStream.LastTokenInStream.Token.SpanStart, 0)))
{
// Formatting is suppressed in the document, and not restored before the end
return;
}
// remove all trailing indentation
var triviaInfo = context.TokenStream.GetTriviaDataAtEndOfTree().WithIndentation(0, context, _formattingRules, cancellationToken);
triviaInfo.Format(context, _formattingRules, EndOfTreeTriviaInfoApplier, cancellationToken);
return;
// local functions
static void EndOfTreeTriviaInfoApplier(int i, TokenStream ts, TriviaData info)
=> ts.ApplyEndOfTreeChange(info);
}
[PerformanceSensitive("https://github.com/dotnet/roslyn/issues/30819", AllowCaptures = false)]
private void ApplyTriviaOperations(FormattingContext context, CancellationToken cancellationToken)
{
for (var i = 0; i < context.TokenStream.TokenCount - 1; i++)
{
cancellationToken.ThrowIfCancellationRequested();
TriviaFormatter(i, context, _formattingRules, cancellationToken);
}
return;
// local functions
static void RegularApplier(int tokenPairIndex, TokenStream ts, TriviaData info)
=> ts.ApplyChange(tokenPairIndex, info);
static void TriviaFormatter(int tokenPairIndex, FormattingContext ctx, ChainedFormattingRules formattingRules, CancellationToken ct)
{
if (ctx.IsFormattingDisabled(tokenPairIndex))
{
return;
}
var triviaInfo = ctx.TokenStream.GetTriviaData(tokenPairIndex);
triviaInfo.Format(
ctx,
formattingRules,
(tokenPairIndex1, ts, info) => RegularApplier(tokenPairIndex1, ts, info),
ct,
tokenPairIndex);
}
}
private TextSpan GetSpanToFormat()
{
var startPosition = this.TreeData.IsFirstToken(_token1) ? this.TreeData.StartPosition : _token1.SpanStart;
var endPosition = this.TreeData.IsLastToken(_token2) ? this.TreeData.EndPosition : _token2.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private static void ApplySpecialOperations(
FormattingContext context, NodeOperations nodeOperationsCollector, OperationApplier applier, CancellationToken cancellationToken)
{
// apply alignment operation
using (Logger.LogBlock(FunctionId.Formatting_CollectAlignOperation, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
// TODO : figure out a way to run alignment operations in parallel. probably find
// unions and run each chunk in separate tasks
var previousChangesMap = new Dictionary<SyntaxToken, int>();
var alignmentOperations = nodeOperationsCollector.AlignmentOperation;
alignmentOperations.Do(operation =>
{
cancellationToken.ThrowIfCancellationRequested();
applier.ApplyAlignment(operation, previousChangesMap, cancellationToken);
});
// go through all relative indent block operation, and see whether it is affected by previous operations
context.GetAllRelativeIndentBlockOperations().Do(o =>
{
cancellationToken.ThrowIfCancellationRequested();
applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken);
});
}
}
private static void ApplyAnchorOperations(
FormattingContext context,
SegmentedArray<TokenPairWithOperations> tokenOperations,
OperationApplier applier,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_ApplyAnchorOperation, cancellationToken))
{
// TODO: find out a way to apply anchor operation concurrently if possible
var previousChangesMap = new Dictionary<SyntaxToken, int>();
foreach (var p in tokenOperations)
{
cancellationToken.ThrowIfCancellationRequested();
if (!AnchorOperationCandidate(p))
{
continue;
}
var pairIndex = p.PairIndex;
applier.ApplyAnchorIndentation(pairIndex, previousChangesMap, cancellationToken);
}
// go through all relative indent block operation, and see whether it is affected by the anchor operation
context.GetAllRelativeIndentBlockOperations().Do(o =>
{
cancellationToken.ThrowIfCancellationRequested();
applier.ApplyBaseTokenIndentationChangesFromTo(FindCorrectBaseTokenOfRelativeIndentBlockOperation(o, context.TokenStream), o.StartToken, o.EndToken, previousChangesMap, cancellationToken);
});
}
}
private static bool AnchorOperationCandidate(TokenPairWithOperations pair)
{
if (pair.LineOperation == null)
{
return pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine;
}
if (pair.LineOperation.Option == AdjustNewLinesOption.ForceLinesIfOnSingleLine)
{
return !pair.TokenStream.TwoTokensOriginallyOnSameLine(pair.Token1, pair.Token2) &&
pair.TokenStream.GetTriviaData(pair.PairIndex).SecondTokenIsFirstTokenOnLine;
}
return false;
}
private static SyntaxToken FindCorrectBaseTokenOfRelativeIndentBlockOperation(IndentBlockOperation operation, TokenStream tokenStream)
{
if (operation.Option.IsOn(IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine))
{
return tokenStream.FirstTokenOfBaseTokenLine(operation.BaseToken);
}
return operation.BaseToken;
}
private static void ApplySpaceAndWrappingOperations(
FormattingContext context,
SegmentedArray<TokenPairWithOperations> tokenOperations,
OperationApplier applier,
CancellationToken cancellationToken)
{
using (Logger.LogBlock(FunctionId.Formatting_ApplySpaceAndLine, cancellationToken))
{
// go through each token pairs and apply operations
foreach (var operationPair in tokenOperations)
{
ApplySpaceAndWrappingOperationsBody(context, operationPair, applier, cancellationToken);
}
}
}
private static void ApplySpaceAndWrappingOperationsBody(
FormattingContext context,
TokenPairWithOperations operation,
OperationApplier applier,
CancellationToken cancellationToken)
{
var token1 = operation.Token1;
var token2 = operation.Token2;
// check whether one of tokens is missing (which means syntax error exist around two tokens)
// in error case, we leave code as user wrote
if (token1.IsMissing || token2.IsMissing)
{
return;
}
var triviaInfo = context.TokenStream.GetTriviaData(operation.PairIndex);
var spanBetweenTokens = TextSpan.FromBounds(token1.Span.End, token2.SpanStart);
if (operation.LineOperation != null)
{
if (!context.IsWrappingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic))
{
// TODO : need to revisit later for the case where line and space operations
// are conflicting each other by forcing new lines and removing new lines.
//
// if wrapping operation applied, no need to run any other operation
if (applier.Apply(operation.LineOperation, operation.PairIndex, cancellationToken))
{
return;
}
}
}
if (operation.SpaceOperation != null)
{
if (!context.IsSpacingSuppressed(spanBetweenTokens, triviaInfo.TreatAsElastic))
{
applier.Apply(operation.SpaceOperation, operation.PairIndex);
}
}
}
private static void BuildContext(
FormattingContext context,
NodeOperations nodeOperations,
CancellationToken cancellationToken)
{
// add scope operation (run each kind sequentially)
using (Logger.LogBlock(FunctionId.Formatting_BuildContext, cancellationToken))
{
cancellationToken.ThrowIfCancellationRequested();
context.AddIndentBlockOperations(nodeOperations.IndentBlockOperation, cancellationToken);
context.AddSuppressOperations(nodeOperations.SuppressOperation, cancellationToken);
}
}
/// <summary>
/// return summary for current formatting work
/// </summary>
private string FormatSummary()
{
return string.Format("({0}) ({1} - {2})",
this.SpanToFormat,
_token1.ToString().Replace("\r\n", "\\r\\n"),
_token2.ToString().Replace("\r\n", "\\r\\n"));
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/VisualBasic/Portable/Completion/KeywordRecommenders/ArrayStatements/ReDimKeywordRecommender.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.ArrayStatements
''' <summary>
''' Recommends the "ReDim" statement.
''' </summary>
Friend Class ReDimKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("ReDim", VBFeaturesResources.Reallocates_storage_space_for_an_array_variable))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Threading
Imports Microsoft.CodeAnalysis.Completion.Providers
Imports Microsoft.CodeAnalysis.VisualBasic.Extensions.ContextQuery
Namespace Microsoft.CodeAnalysis.VisualBasic.Completion.KeywordRecommenders.ArrayStatements
''' <summary>
''' Recommends the "ReDim" statement.
''' </summary>
Friend Class ReDimKeywordRecommender
Inherits AbstractKeywordRecommender
Private Shared ReadOnly s_keywords As ImmutableArray(Of RecommendedKeyword) =
ImmutableArray.Create(New RecommendedKeyword("ReDim", VBFeaturesResources.Reallocates_storage_space_for_an_array_variable))
Protected Overrides Function RecommendKeywords(context As VisualBasicSyntaxContext, cancellationToken As CancellationToken) As ImmutableArray(Of RecommendedKeyword)
Return If(context.IsSingleLineStatementContext, s_keywords, ImmutableArray(Of RecommendedKeyword).Empty)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/CSharp/Test/Emit/PDB/PortablePdbTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET 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.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
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 Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PortablePdbTests : CSharpPDBTestBase
{
[Fact]
public void SequencePointBlob()
{
string source = @"
class C
{
public static void Main()
{
if (F())
{
System.Console.WriteLine(1);
}
}
public static bool F() => false;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
using (var peReader = new PEReader(peBlob))
using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable()))
{
var mdReader = peReader.GetMetadataReader();
var pdbReader = pdbMetadata.Reader;
foreach (var methodHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(methodHandle);
var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle);
var name = mdReader.GetString(method.Name);
TextWriter writer = new StringWriter();
foreach (var sp in methodDebugInfo.GetSequencePoints())
{
if (sp.IsHidden)
{
writer.WriteLine($"{sp.Offset}: <hidden>");
}
else
{
writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})");
}
}
var spString = writer.ToString();
var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob);
switch (name)
{
case "Main":
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
0: (5,5)-(5,6)
1: (6,9)-(6,17)
7: <hidden>
10: (7,9)-(7,10)
11: (8,13)-(8,41)
18: (9,9)-(9,10)
19: (10,5)-(10,6)
", spString);
AssertEx.Equal(new byte[]
{
0x01, // local signature
0x00, // IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x05, // Start Line
0x05, // Start Column
0x01, // delta IL offset
0x00, // Delta Lines
0x08, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x06, // delta IL offset
0x00, // hidden
0x00, // hidden
0x03, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x00, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x1C, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x07, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
}, spBlob);
break;
case "F":
AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString);
AssertEx.Equal(new byte[]
{
0x00, // local signature
0x00, // delta IL offset
0x00, // Delta Lines
0x05, // Delta Columns
0x0C, // Start Line
0x1F // Start Column
}, spBlob);
break;
}
}
}
}
[Fact]
public void EmbeddedPortablePdb()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbFilePath(@"a/b/c/d.pdb").
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA512));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var embedded = entries[2];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA512", checksumData.AlgorithmName);
Assert.Equal(64, checksumData.Checksum.Length);
}
}
[Fact]
public void EmbeddedPortablePdb_Deterministic()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true));
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA384).
WithPdbFilePath(@"a/b/c/d.pdb"));
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];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA384", checksumData.AlgorithmName);
Assert.Equal(48, checksumData.Checksum.Length);
// Reproducible entry:
Assert.Equal(0, reproducible.MajorVersion);
Assert.Equal(0, reproducible.MinorVersion);
Assert.Equal(0U, reproducible.Stamp);
Assert.Equal(0, reproducible.DataSize);
}
}
[Fact]
public void SourceLink()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob));
pdbStream.Position = 0;
using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
{
var pdbReader = provider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
[Fact]
public void SourceLink_Embedded()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob));
using (var peReader = new PEReader(peBlob))
{
var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry))
{
var pdbReader = embeddedMetadataProvider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
}
[Fact]
public void SourceLink_Errors()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); });
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Error!'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 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.
#nullable disable
using System;
using System.IO;
using System.Linq;
using System.Reflection.Metadata;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
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 Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests.PDB
{
public class PortablePdbTests : CSharpPDBTestBase
{
[Fact]
public void SequencePointBlob()
{
string source = @"
class C
{
public static void Main()
{
if (F())
{
System.Console.WriteLine(1);
}
}
public static bool F() => false;
}
";
var c = CreateCompilation(source, options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream);
using (var peReader = new PEReader(peBlob))
using (var pdbMetadata = new PinnedMetadata(pdbStream.ToImmutable()))
{
var mdReader = peReader.GetMetadataReader();
var pdbReader = pdbMetadata.Reader;
foreach (var methodHandle in mdReader.MethodDefinitions)
{
var method = mdReader.GetMethodDefinition(methodHandle);
var methodDebugInfo = pdbReader.GetMethodDebugInformation(methodHandle);
var name = mdReader.GetString(method.Name);
TextWriter writer = new StringWriter();
foreach (var sp in methodDebugInfo.GetSequencePoints())
{
if (sp.IsHidden)
{
writer.WriteLine($"{sp.Offset}: <hidden>");
}
else
{
writer.WriteLine($"{sp.Offset}: ({sp.StartLine},{sp.StartColumn})-({sp.EndLine},{sp.EndColumn})");
}
}
var spString = writer.ToString();
var spBlob = pdbReader.GetBlobBytes(methodDebugInfo.SequencePointsBlob);
switch (name)
{
case "Main":
AssertEx.AssertEqualToleratingWhitespaceDifferences(@"
0: (5,5)-(5,6)
1: (6,9)-(6,17)
7: <hidden>
10: (7,9)-(7,10)
11: (8,13)-(8,41)
18: (9,9)-(9,10)
19: (10,5)-(10,6)
", spString);
AssertEx.Equal(new byte[]
{
0x01, // local signature
0x00, // IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x05, // Start Line
0x05, // Start Column
0x01, // delta IL offset
0x00, // Delta Lines
0x08, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x06, // delta IL offset
0x00, // hidden
0x00, // hidden
0x03, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x00, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x1C, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x08, // delta Start Column (signed compressed)
0x07, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
0x01, // delta IL offset
0x00, // Delta Lines
0x01, // Delta Columns
0x02, // delta Start Line (signed compressed)
0x79, // delta Start Column (signed compressed)
}, spBlob);
break;
case "F":
AssertEx.AssertEqualToleratingWhitespaceDifferences("0: (12,31)-(12,36)", spString);
AssertEx.Equal(new byte[]
{
0x00, // local signature
0x00, // delta IL offset
0x00, // Delta Lines
0x05, // Delta Columns
0x0C, // Start Line
0x1F // Start Column
}, spBlob);
break;
}
}
}
}
[Fact]
public void EmbeddedPortablePdb()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbFilePath(@"a/b/c/d.pdb").
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA512));
using (var peReader = new PEReader(peBlob))
{
var entries = peReader.ReadDebugDirectory();
AssertEx.Equal(new[] { DebugDirectoryEntryType.CodeView, DebugDirectoryEntryType.PdbChecksum, DebugDirectoryEntryType.EmbeddedPortablePdb }, entries.Select(e => e.Type));
var codeView = entries[0];
var checksum = entries[1];
var embedded = entries[2];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA512", checksumData.AlgorithmName);
Assert.Equal(64, checksumData.Checksum.Length);
}
}
[Fact]
public void EmbeddedPortablePdb_Deterministic()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var c = CreateCompilation(Parse(source, "goo.cs"), options: TestOptions.DebugDll.WithDeterministic(true));
var peBlob = c.EmitToArray(EmitOptions.Default.
WithDebugInformationFormat(DebugInformationFormat.Embedded).
WithPdbChecksumAlgorithm(HashAlgorithmName.SHA384).
WithPdbFilePath(@"a/b/c/d.pdb"));
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];
// EmbeddedPortablePdb entry:
Assert.Equal(0x0100, embedded.MajorVersion);
Assert.Equal(0x0100, embedded.MinorVersion);
Assert.Equal(0u, embedded.Stamp);
BlobContentId pdbId;
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embedded))
{
var mdReader = embeddedMetadataProvider.GetMetadataReader();
AssertEx.Equal(new[] { "goo.cs" }, mdReader.Documents.Select(doc => mdReader.GetString(mdReader.GetDocument(doc).Name)));
pdbId = new BlobContentId(mdReader.DebugMetadataHeader.Id);
}
// CodeView entry:
var codeViewData = peReader.ReadCodeViewDebugDirectoryData(codeView);
Assert.Equal(0x0100, codeView.MajorVersion);
Assert.Equal(0x504D, codeView.MinorVersion);
Assert.Equal(pdbId.Stamp, codeView.Stamp);
Assert.Equal(pdbId.Guid, codeViewData.Guid);
Assert.Equal("d.pdb", codeViewData.Path);
// Checksum entry:
var checksumData = peReader.ReadPdbChecksumDebugDirectoryData(checksum);
Assert.Equal("SHA384", checksumData.AlgorithmName);
Assert.Equal(48, checksumData.Checksum.Length);
// Reproducible entry:
Assert.Equal(0, reproducible.MajorVersion);
Assert.Equal(0, reproducible.MinorVersion);
Assert.Equal(0U, reproducible.Stamp);
Assert.Equal(0, reproducible.DataSize);
}
}
[Fact]
public void SourceLink()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var pdbStream = new MemoryStream();
c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), pdbStream: pdbStream, sourceLinkStream: new MemoryStream(sourceLinkBlob));
pdbStream.Position = 0;
using (var provider = MetadataReaderProvider.FromPortablePdbStream(pdbStream))
{
var pdbReader = provider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
[Fact]
public void SourceLink_Embedded()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkBlob = Encoding.UTF8.GetBytes(@"
{
""documents"": {
""f:/build/*"" : ""https://raw.githubusercontent.com/my-org/my-project/1111111111111111111111111111111111111111/*""
}
}
");
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var peBlob = c.EmitToArray(EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.Embedded), sourceLinkStream: new MemoryStream(sourceLinkBlob));
using (var peReader = new PEReader(peBlob))
{
var embeddedEntry = peReader.ReadDebugDirectory().Single(e => e.Type == DebugDirectoryEntryType.EmbeddedPortablePdb);
using (var embeddedMetadataProvider = peReader.ReadEmbeddedPortablePdbDebugDirectoryData(embeddedEntry))
{
var pdbReader = embeddedMetadataProvider.GetMetadataReader();
var actualBlob =
(from cdiHandle in pdbReader.GetCustomDebugInformation(EntityHandle.ModuleDefinition)
let cdi = pdbReader.GetCustomDebugInformation(cdiHandle)
where pdbReader.GetGuid(cdi.Kind) == PortableCustomDebugInfoKinds.SourceLink
select pdbReader.GetBlobBytes(cdi.Value)).Single();
AssertEx.Equal(sourceLinkBlob, actualBlob);
}
}
}
[Fact]
public void SourceLink_Errors()
{
string source = @"
using System;
class C
{
public static void Main()
{
Console.WriteLine();
}
}
";
var sourceLinkStream = new TestStream(canRead: true, readFunc: (_, __, ___) => { throw new Exception("Error!"); });
var c = CreateCompilation(Parse(source, "f:/build/goo.cs"), options: TestOptions.DebugDll);
var result = c.Emit(new MemoryStream(), new MemoryStream(), options: EmitOptions.Default.WithDebugInformationFormat(DebugInformationFormat.PortablePdb), sourceLinkStream: sourceLinkStream);
result.Diagnostics.Verify(
// error CS0041: Unexpected error writing debug information -- 'Error!'
Diagnostic(ErrorCode.FTL_DebugEmitFailure).WithArguments("Error!").WithLocation(1, 1));
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/Implementation/Diagnostics/AbstractDiagnosticsAdornmentTaggerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics
{
internal abstract class AbstractDiagnosticsAdornmentTaggerProvider<TTag> :
AbstractDiagnosticsTaggerProvider<TTag>
where TTag : class, ITag
{
public AbstractDiagnosticsAdornmentTaggerProvider(
IThreadingContext threadingContext,
IDiagnosticService diagnosticService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorSquiggles))
{
}
protected internal sealed override bool IsEnabled => true;
protected internal sealed override ITagSpan<TTag>? CreateTagSpan(
Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data)
{
var errorTag = CreateTag(workspace, data);
if (errorTag == null)
{
return null;
}
// Live update squiggles have to be at least 1 character long.
var minimumLength = isLiveUpdate ? 1 : 0;
var adjustedSpan = AdjustSnapshotSpan(span, minimumLength);
if (adjustedSpan.Length == 0)
{
return null;
}
return new TagSpan<TTag>(adjustedSpan, errorTag);
}
protected static object CreateToolTipContent(Workspace workspace, DiagnosticData diagnostic)
{
Action? navigationAction = null;
string? tooltip = null;
if (workspace is object
&& diagnostic.HelpLink is { } helpLink
&& Uri.TryCreate(helpLink, UriKind.Absolute, out var helpLinkUri))
{
navigationAction = new QuickInfoHyperLink(workspace, helpLinkUri).NavigationAction;
tooltip = helpLink;
}
var diagnosticIdTextRun = navigationAction is null
? new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id)
: new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id, navigationAction, tooltip);
return new ContainerElement(
ContainerElementStyle.Wrapped,
new ClassifiedTextElement(
diagnosticIdTextRun,
new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Message)));
}
protected virtual SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength)
=> AdjustSnapshotSpan(span, minimumLength, int.MaxValue);
protected static SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength, int maximumLength)
{
var snapshot = span.Snapshot;
// new length
var length = Math.Min(Math.Max(span.Length, minimumLength), maximumLength);
// make sure start + length is smaller than snapshot.Length and start is >= 0
var start = Math.Max(0, Math.Min(span.Start, snapshot.Length - length));
// make sure length is smaller than snapshot.Length which can happen if start == 0
return new SnapshotSpan(snapshot, start, Math.Min(start + length, snapshot.Length) - start);
}
protected abstract TTag? CreateTag(Workspace workspace, DiagnosticData diagnostic);
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.CodeAnalysis.Classification;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.Implementation.IntelliSense.QuickInfo;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Adornments;
using Microsoft.VisualStudio.Text.Tagging;
namespace Microsoft.CodeAnalysis.Editor.Implementation.Diagnostics
{
internal abstract class AbstractDiagnosticsAdornmentTaggerProvider<TTag> :
AbstractDiagnosticsTaggerProvider<TTag>
where TTag : class, ITag
{
public AbstractDiagnosticsAdornmentTaggerProvider(
IThreadingContext threadingContext,
IDiagnosticService diagnosticService,
IAsynchronousOperationListenerProvider listenerProvider)
: base(threadingContext, diagnosticService, listenerProvider.GetListener(FeatureAttribute.ErrorSquiggles))
{
}
protected internal sealed override bool IsEnabled => true;
protected internal sealed override ITagSpan<TTag>? CreateTagSpan(
Workspace workspace, bool isLiveUpdate, SnapshotSpan span, DiagnosticData data)
{
var errorTag = CreateTag(workspace, data);
if (errorTag == null)
{
return null;
}
// Live update squiggles have to be at least 1 character long.
var minimumLength = isLiveUpdate ? 1 : 0;
var adjustedSpan = AdjustSnapshotSpan(span, minimumLength);
if (adjustedSpan.Length == 0)
{
return null;
}
return new TagSpan<TTag>(adjustedSpan, errorTag);
}
protected static object CreateToolTipContent(Workspace workspace, DiagnosticData diagnostic)
{
Action? navigationAction = null;
string? tooltip = null;
if (workspace is object
&& diagnostic.HelpLink is { } helpLink
&& Uri.TryCreate(helpLink, UriKind.Absolute, out var helpLinkUri))
{
navigationAction = new QuickInfoHyperLink(workspace, helpLinkUri).NavigationAction;
tooltip = helpLink;
}
var diagnosticIdTextRun = navigationAction is null
? new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id)
: new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Id, navigationAction, tooltip);
return new ContainerElement(
ContainerElementStyle.Wrapped,
new ClassifiedTextElement(
diagnosticIdTextRun,
new ClassifiedTextRun(ClassificationTypeNames.Punctuation, ":"),
new ClassifiedTextRun(ClassificationTypeNames.WhiteSpace, " "),
new ClassifiedTextRun(ClassificationTypeNames.Text, diagnostic.Message)));
}
protected virtual SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength)
=> AdjustSnapshotSpan(span, minimumLength, int.MaxValue);
protected static SnapshotSpan AdjustSnapshotSpan(SnapshotSpan span, int minimumLength, int maximumLength)
{
var snapshot = span.Snapshot;
// new length
var length = Math.Min(Math.Max(span.Length, minimumLength), maximumLength);
// make sure start + length is smaller than snapshot.Length and start is >= 0
var start = Math.Max(0, Math.Min(span.Start, snapshot.Length - length));
// make sure length is smaller than snapshot.Length which can happen if start == 0
return new SnapshotSpan(snapshot, start, Math.Min(start + length, snapshot.Length) - start);
}
protected abstract TTag? CreateTag(Workspace workspace, DiagnosticData diagnostic);
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/VisualBasic/ChangeSignature/VisualBasicChangeSignatureCommandHandler.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.ComponentModel.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.ChangeSignature
<Export(GetType(ICommandHandler))>
<ContentType(ContentTypeNames.VisualBasicContentType)>
<Name(PredefinedCommandHandlerNames.ChangeSignature)>
Friend Class VisualBasicChangeSignatureCommandHandler
Inherits AbstractChangeSignatureCommandHandler
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(threadingContext As IThreadingContext)
MyBase.New(threadingContext)
End Sub
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.ComponentModel.Composition
Imports System.Diagnostics.CodeAnalysis
Imports Microsoft.CodeAnalysis.Editor.Implementation.ChangeSignature
Imports Microsoft.CodeAnalysis.Editor.[Shared].Utilities
Imports Microsoft.VisualStudio.Commanding
Imports Microsoft.VisualStudio.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.ChangeSignature
<Export(GetType(ICommandHandler))>
<ContentType(ContentTypeNames.VisualBasicContentType)>
<Name(PredefinedCommandHandlerNames.ChangeSignature)>
Friend Class VisualBasicChangeSignatureCommandHandler
Inherits AbstractChangeSignatureCommandHandler
<ImportingConstructor>
<SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")>
Public Sub New(threadingContext As IThreadingContext)
MyBase.New(threadingContext)
End Sub
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/Core/Portable/Completion/Providers/ImportCompletionProvider/AbstractImportCompletionCacheServiceFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// 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.Concurrent;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion
{
internal abstract class AbstractImportCompletionCacheServiceFactory<TProjectCacheEntry, TMetadataCacheEntry> : IWorkspaceServiceFactory
{
private readonly ConcurrentDictionary<string, TMetadataCacheEntry> _peItemsCache
= new();
private readonly ConcurrentDictionary<ProjectId, TProjectCacheEntry> _projectItemsCache
= new();
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var workspace = workspaceServices.Workspace;
if (workspace.Kind == WorkspaceKind.Host)
{
var cacheService = workspaceServices.GetService<IWorkspaceCacheService>();
if (cacheService != null)
{
cacheService.CacheFlushRequested += OnCacheFlushRequested;
}
}
return new ImportCompletionCacheService(_peItemsCache, _projectItemsCache);
}
private void OnCacheFlushRequested(object? sender, EventArgs e)
{
_peItemsCache.Clear();
_projectItemsCache.Clear();
}
private class ImportCompletionCacheService : IImportCompletionCacheService<TProjectCacheEntry, TMetadataCacheEntry>
{
public IDictionary<string, TMetadataCacheEntry> PEItemsCache { get; }
public IDictionary<ProjectId, TProjectCacheEntry> ProjectItemsCache { get; }
public ImportCompletionCacheService(
ConcurrentDictionary<string, TMetadataCacheEntry> peCache,
ConcurrentDictionary<ProjectId, TProjectCacheEntry> projectCache)
{
PEItemsCache = peCache;
ProjectItemsCache = projectCache;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// 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.Concurrent;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion
{
internal abstract class AbstractImportCompletionCacheServiceFactory<TProjectCacheEntry, TMetadataCacheEntry> : IWorkspaceServiceFactory
{
private readonly ConcurrentDictionary<string, TMetadataCacheEntry> _peItemsCache
= new();
private readonly ConcurrentDictionary<ProjectId, TProjectCacheEntry> _projectItemsCache
= new();
public IWorkspaceService CreateService(HostWorkspaceServices workspaceServices)
{
var workspace = workspaceServices.Workspace;
if (workspace.Kind == WorkspaceKind.Host)
{
var cacheService = workspaceServices.GetService<IWorkspaceCacheService>();
if (cacheService != null)
{
cacheService.CacheFlushRequested += OnCacheFlushRequested;
}
}
return new ImportCompletionCacheService(_peItemsCache, _projectItemsCache);
}
private void OnCacheFlushRequested(object? sender, EventArgs e)
{
_peItemsCache.Clear();
_projectItemsCache.Clear();
}
private class ImportCompletionCacheService : IImportCompletionCacheService<TProjectCacheEntry, TMetadataCacheEntry>
{
public IDictionary<string, TMetadataCacheEntry> PEItemsCache { get; }
public IDictionary<ProjectId, TProjectCacheEntry> ProjectItemsCache { get; }
public ImportCompletionCacheService(
ConcurrentDictionary<string, TMetadataCacheEntry> peCache,
ConcurrentDictionary<ProjectId, TProjectCacheEntry> projectCache)
{
PEItemsCache = peCache;
ProjectItemsCache = projectCache;
}
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/VisualBasicTest/Semantics/SpeculationAnalyzerTests.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.IO
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Semantics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Semantics
Public Class SpeculationAnalyzerTests
Inherits SpeculationAnalyzerTestsBase
<Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")>
Public Sub SpeculationAnalyzerExtensionMethodExplicitInvocation()
Test(<Code>
Module Oombr
<System.Runtime.CompilerServices.Extension>
Public Sub Vain(arg As Integer)
End Sub
Sub Main()
Call [|5.Vain()|]
End Sub
End Module
</Code>.Value, "Vain(5)", False)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerIndexerPropertyWithRedundantCast()
Test(<Code>
Class Indexer
Default Public ReadOnly Property Item(ByVal x As Integer) As Integer
Get
Return x
End Get
End Property
End Class
Class A
Public ReadOnly Property Foo As Indexer
End Class
Class B
Inherits A
End Class
Class Program
Sub Main()
Dim b As B = New B()
Dim y As Integer = [|DirectCast(b, A)|].Foo(2)
End Sub
End Class
</Code>.Value, "b", False)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerIndexerPropertyWithRequiredCast()
Test(<Code>
Class Indexer
Default Public ReadOnly Property Item(ByVal x As Integer) As Integer
Get
Return x
End Get
End Property
End Class
Class A
Public ReadOnly Property Foo As Indexer
End Class
Class B
Inherits A
Public Shadows ReadOnly Property Foo As Indexer
End Class
Class Program
Sub Main()
Dim b As B = New B()
Dim y As Integer = [|DirectCast(b, A)|].Foo(2)
End Sub
End Class
</Code>.Value, "b", True)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerDelegatePropertyWithRedundantCast()
Test(<Code>
Public Delegate Sub MyDelegate()
Class A
Public ReadOnly Property Foo As MyDelegate
End Class
Class B
Inherits A
End Class
Class Program
Sub Main()
Dim b As B = New B()
[|DirectCast(b, A)|].Foo.Invoke()
End Sub
End Class
</Code>.Value, "b", False)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerDelegatePropertyWithRequiredCast()
Test(<Code>
Public Delegate Sub MyDelegate()
Class A
Public ReadOnly Property Foo As MyDelegate
End Class
Class B
Inherits A
Public Shadows ReadOnly Property Foo As MyDelegate
End Class
Class Program
Sub Main()
Dim b As B = New B()
[|DirectCast(b, A)|].Foo.Invoke()
End Sub
End Class
</Code>.Value, "b", True)
End Sub
Protected Overrides Function Parse(text As String) As SyntaxTree
Return SyntaxFactory.ParseSyntaxTree(text)
End Function
Protected Overrides Function IsExpressionNode(node As SyntaxNode) As Boolean
Return TypeOf node Is ExpressionSyntax
End Function
Protected Overrides Function CreateCompilation(tree As SyntaxTree) As Compilation
Return VisualBasicCompilation.Create(
CompilationName,
{DirectCast(tree, VisualBasicSyntaxTree)},
References,
TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC0219", ReportDiagnostic.Suppress)}))
End Function
Protected Overrides Function CompilationSucceeded(compilation As Compilation, temporaryStream As Stream) As Boolean
Dim langCompilation = DirectCast(compilation, VisualBasicCompilation)
Return Not langCompilation.GetDiagnostics().Any() AndAlso Not langCompilation.Emit(temporaryStream).Diagnostics.Any()
End Function
Protected Overrides Function ReplacementChangesSemantics(initialNode As SyntaxNode, replacementNode As SyntaxNode, initialModel As SemanticModel) As Boolean
Return New SpeculationAnalyzer(DirectCast(initialNode, ExpressionSyntax), DirectCast(replacementNode, ExpressionSyntax), initialModel, CancellationToken.None).ReplacementChangesSemantics()
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.IO
Imports System.Threading
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Semantics
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Imports Microsoft.CodeAnalysis.VisualBasic.Utilities
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Semantics
Public Class SpeculationAnalyzerTests
Inherits SpeculationAnalyzerTestsBase
<Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")>
Public Sub SpeculationAnalyzerExtensionMethodExplicitInvocation()
Test(<Code>
Module Oombr
<System.Runtime.CompilerServices.Extension>
Public Sub Vain(arg As Integer)
End Sub
Sub Main()
Call [|5.Vain()|]
End Sub
End Module
</Code>.Value, "Vain(5)", False)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerIndexerPropertyWithRedundantCast()
Test(<Code>
Class Indexer
Default Public ReadOnly Property Item(ByVal x As Integer) As Integer
Get
Return x
End Get
End Property
End Class
Class A
Public ReadOnly Property Foo As Indexer
End Class
Class B
Inherits A
End Class
Class Program
Sub Main()
Dim b As B = New B()
Dim y As Integer = [|DirectCast(b, A)|].Foo(2)
End Sub
End Class
</Code>.Value, "b", False)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerIndexerPropertyWithRequiredCast()
Test(<Code>
Class Indexer
Default Public ReadOnly Property Item(ByVal x As Integer) As Integer
Get
Return x
End Get
End Property
End Class
Class A
Public ReadOnly Property Foo As Indexer
End Class
Class B
Inherits A
Public Shadows ReadOnly Property Foo As Indexer
End Class
Class Program
Sub Main()
Dim b As B = New B()
Dim y As Integer = [|DirectCast(b, A)|].Foo(2)
End Sub
End Class
</Code>.Value, "b", True)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerDelegatePropertyWithRedundantCast()
Test(<Code>
Public Delegate Sub MyDelegate()
Class A
Public ReadOnly Property Foo As MyDelegate
End Class
Class B
Inherits A
End Class
Class Program
Sub Main()
Dim b As B = New B()
[|DirectCast(b, A)|].Foo.Invoke()
End Sub
End Class
</Code>.Value, "b", False)
End Sub
<Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")>
Public Sub SpeculationAnalyzerDelegatePropertyWithRequiredCast()
Test(<Code>
Public Delegate Sub MyDelegate()
Class A
Public ReadOnly Property Foo As MyDelegate
End Class
Class B
Inherits A
Public Shadows ReadOnly Property Foo As MyDelegate
End Class
Class Program
Sub Main()
Dim b As B = New B()
[|DirectCast(b, A)|].Foo.Invoke()
End Sub
End Class
</Code>.Value, "b", True)
End Sub
Protected Overrides Function Parse(text As String) As SyntaxTree
Return SyntaxFactory.ParseSyntaxTree(text)
End Function
Protected Overrides Function IsExpressionNode(node As SyntaxNode) As Boolean
Return TypeOf node Is ExpressionSyntax
End Function
Protected Overrides Function CreateCompilation(tree As SyntaxTree) As Compilation
Return VisualBasicCompilation.Create(
CompilationName,
{DirectCast(tree, VisualBasicSyntaxTree)},
References,
TestOptions.ReleaseDll.WithSpecificDiagnosticOptions({KeyValuePairUtil.Create("BC0219", ReportDiagnostic.Suppress)}))
End Function
Protected Overrides Function CompilationSucceeded(compilation As Compilation, temporaryStream As Stream) As Boolean
Dim langCompilation = DirectCast(compilation, VisualBasicCompilation)
Return Not langCompilation.GetDiagnostics().Any() AndAlso Not langCompilation.Emit(temporaryStream).Diagnostics.Any()
End Function
Protected Overrides Function ReplacementChangesSemantics(initialNode As SyntaxNode, replacementNode As SyntaxNode, initialModel As SemanticModel) As Boolean
Return New SpeculationAnalyzer(DirectCast(initialNode, ExpressionSyntax), DirectCast(replacementNode, ExpressionSyntax), initialModel, CancellationToken.None).ReplacementChangesSemantics()
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/VisualBasic/Portable/Emit/PEAssemblyBuilder.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Reflection
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend MustInherit Class PEAssemblyBuilderBase
Inherits PEModuleBuilder
Implements Cci.IAssemblyReference
Protected ReadOnly m_SourceAssembly As SourceAssemblySymbol
Private ReadOnly _additionalTypes As ImmutableArray(Of NamedTypeSymbol)
Private _lazyFiles As ImmutableArray(Of Cci.IFileReference)
''' <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary>
Private _lazyFilesWithoutManifestResources As ImmutableArray(Of Cci.IFileReference)
''' <summary>
''' This value will override m_SourceModule.MetadataName.
''' </summary>
''' <remarks>
''' This functionality exists for parity with C#, which requires it for
''' legacy reasons (see Microsoft.CodeAnalysis.CSharp.Emit.PEAssemblyBuilderBase.metadataName).
''' </remarks>
Private ReadOnly _metadataName As String
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
additionalTypes As ImmutableArray(Of NamedTypeSymbol))
MyBase.New(DirectCast(sourceAssembly.Modules(0), SourceModuleSymbol),
emitOptions,
outputKind,
serializationProperties,
manifestResources)
Debug.Assert(sourceAssembly IsNot Nothing)
Debug.Assert(manifestResources IsNot Nothing)
m_SourceAssembly = sourceAssembly
_additionalTypes = additionalTypes.NullToEmpty()
_metadataName = If(emitOptions.OutputNameOverride Is Nothing, sourceAssembly.MetadataName, FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension:=Nothing))
m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, Me)
End Sub
Public Overrides ReadOnly Property SourceAssemblyOpt As ISourceAssemblySymbolInternal
Get
Return m_SourceAssembly
End Get
End Property
Public Overrides Function GetAdditionalTopLevelTypes() As ImmutableArray(Of NamedTypeSymbol)
Return _additionalTypes
End Function
Public Overrides Function GetEmbeddedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public NotOverridable Overrides Function GetFiles(context As EmitContext) As IEnumerable(Of Cci.IFileReference)
If Not context.IsRefAssembly Then
Return GetFilesCore(context, _lazyFiles)
End If
Return GetFilesCore(context, _lazyFilesWithoutManifestResources)
End Function
Private Function GetFilesCore(context As EmitContext, ByRef lazyFiles As ImmutableArray(Of Cci.IFileReference)) As IEnumerable(Of Cci.IFileReference)
If lazyFiles.IsDefault Then
Dim builder = ArrayBuilder(Of Cci.IFileReference).GetInstance()
Try
Dim modules = m_SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
builder.Add(DirectCast(Translate(modules(i), context.Diagnostics), Cci.IFileReference))
Next
If Not context.IsRefAssembly Then
' resources are not emitted into ref assemblies
For Each resource In ManifestResources
If Not resource.IsEmbedded Then
builder.Add(resource)
End If
Next
End If
' Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
If ImmutableInterlocked.InterlockedInitialize(lazyFiles, builder.ToImmutable()) AndAlso lazyFiles.Length > 0 Then
If Not CryptographicHashProvider.IsSupportedAlgorithm(m_SourceAssembly.HashAlgorithm) Then
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_CryptoHashFailed), NoLocation.Singleton))
End If
End If
Finally
' Clean up so we don't get a leak report from the unit tests.
builder.Free()
End Try
End If
Return lazyFiles
End Function
Private Shared Function Free(builder As ArrayBuilder(Of Cci.IFileReference)) As Boolean
builder.Free()
Return False
End Function
Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag)
Dim modules = m_SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
Dim file = DirectCast(Translate(modules(i), diagnostics), Cci.IFileReference)
Try
For Each resource In DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol).Module.GetEmbeddedResourcesOrThrow()
builder.Add(New Cci.ManagedResource(
resource.Name,
(resource.Attributes And ManifestResourceAttributes.Public) <> 0,
Nothing,
file,
resource.Offset))
Next
Catch mrEx As BadImageFormatException
diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, modules(i))
End Try
Next
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _metadataName
End Get
End Property
Public ReadOnly Property Identity As AssemblyIdentity Implements Cci.IAssemblyReference.Identity
Get
Return m_SourceAssembly.Identity
End Get
End Property
Public ReadOnly Property AssemblyVersionPattern As Version Implements Cci.IAssemblyReference.AssemblyVersionPattern
Get
Return m_SourceAssembly.AssemblyVersionPattern
End Get
End Property
End Class
Friend NotInheritable Class PEAssemblyBuilder
Inherits PEAssemblyBuilderBase
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
Optional additionalTypes As ImmutableArray(Of NamedTypeSymbol) = Nothing)
MyBase.New(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, additionalTypes)
End Sub
Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline
Get
Return Nothing
End Get
End Property
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports System.Collections.Immutable
Imports System.Reflection
Imports Microsoft.CodeAnalysis.Emit
Imports Microsoft.CodeAnalysis.PooledObjects
Imports Microsoft.CodeAnalysis.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Namespace Microsoft.CodeAnalysis.VisualBasic.Emit
Friend MustInherit Class PEAssemblyBuilderBase
Inherits PEModuleBuilder
Implements Cci.IAssemblyReference
Protected ReadOnly m_SourceAssembly As SourceAssemblySymbol
Private ReadOnly _additionalTypes As ImmutableArray(Of NamedTypeSymbol)
Private _lazyFiles As ImmutableArray(Of Cci.IFileReference)
''' <summary>This is a cache of a subset of <seealso cref="_lazyFiles"/>. We don't include manifest resources in ref assemblies</summary>
Private _lazyFilesWithoutManifestResources As ImmutableArray(Of Cci.IFileReference)
''' <summary>
''' This value will override m_SourceModule.MetadataName.
''' </summary>
''' <remarks>
''' This functionality exists for parity with C#, which requires it for
''' legacy reasons (see Microsoft.CodeAnalysis.CSharp.Emit.PEAssemblyBuilderBase.metadataName).
''' </remarks>
Private ReadOnly _metadataName As String
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
additionalTypes As ImmutableArray(Of NamedTypeSymbol))
MyBase.New(DirectCast(sourceAssembly.Modules(0), SourceModuleSymbol),
emitOptions,
outputKind,
serializationProperties,
manifestResources)
Debug.Assert(sourceAssembly IsNot Nothing)
Debug.Assert(manifestResources IsNot Nothing)
m_SourceAssembly = sourceAssembly
_additionalTypes = additionalTypes.NullToEmpty()
_metadataName = If(emitOptions.OutputNameOverride Is Nothing, sourceAssembly.MetadataName, FileNameUtilities.ChangeExtension(emitOptions.OutputNameOverride, extension:=Nothing))
m_AssemblyOrModuleSymbolToModuleRefMap.Add(sourceAssembly, Me)
End Sub
Public Overrides ReadOnly Property SourceAssemblyOpt As ISourceAssemblySymbolInternal
Get
Return m_SourceAssembly
End Get
End Property
Public Overrides Function GetAdditionalTopLevelTypes() As ImmutableArray(Of NamedTypeSymbol)
Return _additionalTypes
End Function
Public Overrides Function GetEmbeddedTypes(diagnostics As DiagnosticBag) As ImmutableArray(Of NamedTypeSymbol)
Return ImmutableArray(Of NamedTypeSymbol).Empty
End Function
Public NotOverridable Overrides Function GetFiles(context As EmitContext) As IEnumerable(Of Cci.IFileReference)
If Not context.IsRefAssembly Then
Return GetFilesCore(context, _lazyFiles)
End If
Return GetFilesCore(context, _lazyFilesWithoutManifestResources)
End Function
Private Function GetFilesCore(context As EmitContext, ByRef lazyFiles As ImmutableArray(Of Cci.IFileReference)) As IEnumerable(Of Cci.IFileReference)
If lazyFiles.IsDefault Then
Dim builder = ArrayBuilder(Of Cci.IFileReference).GetInstance()
Try
Dim modules = m_SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
builder.Add(DirectCast(Translate(modules(i), context.Diagnostics), Cci.IFileReference))
Next
If Not context.IsRefAssembly Then
' resources are not emitted into ref assemblies
For Each resource In ManifestResources
If Not resource.IsEmbedded Then
builder.Add(resource)
End If
Next
End If
' Dev12 compilers don't report ERR_CryptoHashFailed if there are no files to be hashed.
If ImmutableInterlocked.InterlockedInitialize(lazyFiles, builder.ToImmutable()) AndAlso lazyFiles.Length > 0 Then
If Not CryptographicHashProvider.IsSupportedAlgorithm(m_SourceAssembly.HashAlgorithm) Then
context.Diagnostics.Add(New VBDiagnostic(ErrorFactory.ErrorInfo(ERRID.ERR_CryptoHashFailed), NoLocation.Singleton))
End If
End If
Finally
' Clean up so we don't get a leak report from the unit tests.
builder.Free()
End Try
End If
Return lazyFiles
End Function
Private Shared Function Free(builder As ArrayBuilder(Of Cci.IFileReference)) As Boolean
builder.Free()
Return False
End Function
Protected Overrides Sub AddEmbeddedResourcesFromAddedModules(builder As ArrayBuilder(Of Cci.ManagedResource), diagnostics As DiagnosticBag)
Dim modules = m_SourceAssembly.Modules
For i As Integer = 1 To modules.Length - 1
Dim file = DirectCast(Translate(modules(i), diagnostics), Cci.IFileReference)
Try
For Each resource In DirectCast(modules(i), Symbols.Metadata.PE.PEModuleSymbol).Module.GetEmbeddedResourcesOrThrow()
builder.Add(New Cci.ManagedResource(
resource.Name,
(resource.Attributes And ManifestResourceAttributes.Public) <> 0,
Nothing,
file,
resource.Offset))
Next
Catch mrEx As BadImageFormatException
diagnostics.Add(ERRID.ERR_UnsupportedModule1, NoLocation.Singleton, modules(i))
End Try
Next
End Sub
Public Overrides ReadOnly Property Name As String
Get
Return _metadataName
End Get
End Property
Public ReadOnly Property Identity As AssemblyIdentity Implements Cci.IAssemblyReference.Identity
Get
Return m_SourceAssembly.Identity
End Get
End Property
Public ReadOnly Property AssemblyVersionPattern As Version Implements Cci.IAssemblyReference.AssemblyVersionPattern
Get
Return m_SourceAssembly.AssemblyVersionPattern
End Get
End Property
End Class
Friend NotInheritable Class PEAssemblyBuilder
Inherits PEAssemblyBuilderBase
Public Sub New(sourceAssembly As SourceAssemblySymbol,
emitOptions As EmitOptions,
outputKind As OutputKind,
serializationProperties As Cci.ModulePropertiesForSerialization,
manifestResources As IEnumerable(Of ResourceDescription),
Optional additionalTypes As ImmutableArray(Of NamedTypeSymbol) = Nothing)
MyBase.New(sourceAssembly, emitOptions, outputKind, serializationProperties, manifestResources, additionalTypes)
End Sub
Friend Overrides ReadOnly Property AllowOmissionOfConditionalCalls As Boolean
Get
Return True
End Get
End Property
Public Overrides ReadOnly Property EncSymbolChanges As SymbolChanges
Get
Return Nothing
End Get
End Property
Public Overrides ReadOnly Property PreviousGeneration As EmitBaseline
Get
Return Nothing
End Get
End Property
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/VisualStudio/Core/Impl/CodeModel/AbstractCodeModelService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal abstract partial class AbstractCodeModelService : ICodeModelService
{
private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps =
new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>();
protected readonly ISyntaxFactsService SyntaxFactsService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly AbstractNodeNameGenerator _nodeNameGenerator;
private readonly AbstractNodeLocator _nodeLocator;
private readonly AbstractCodeModelEventCollector _eventCollector;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly AbstractFormattingRule _lineAdjustmentFormattingRule;
private readonly AbstractFormattingRule _endRegionFormattingRule;
private readonly IThreadingContext _threadingContext;
protected AbstractCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
AbstractFormattingRule lineAdjustmentFormattingRule,
AbstractFormattingRule endRegionFormattingRule,
IThreadingContext threadingContext)
{
Debug.Assert(languageServiceProvider != null);
Debug.Assert(editorOptionsFactoryService != null);
this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>();
_editorOptionsFactoryService = editorOptionsFactoryService;
_lineAdjustmentFormattingRule = lineAdjustmentFormattingRule;
_endRegionFormattingRule = endRegionFormattingRule;
_threadingContext = threadingContext;
_refactorNotifyServices = refactorNotifyServices;
_nodeNameGenerator = CreateNodeNameGenerator();
_nodeLocator = CreateNodeLocator();
_eventCollector = CreateCodeModelEventCollector();
}
protected string GetNewLineCharacter(SourceText text)
=> _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter();
protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter)
{
while (current.ContainsAnnotations)
{
current = nextTokenGetter(current);
}
return current;
}
protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken)
{
var startPosition = startToken.SpanStart;
var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree)
{
var nameOrdinalMap = new Dictionary<string, int>();
var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty;
foreach (var node in GetFlattenedMemberNodes(syntaxTree))
{
var name = _nodeNameGenerator.GenerateName(node);
if (!nameOrdinalMap.TryGetValue(name, out var ordinal))
{
ordinal = 0;
}
nameOrdinalMap[name] = ++ordinal;
var key = new SyntaxNodeKey(name, ordinal);
nodeKeyMap = nodeKeyMap.Add(key, node);
}
return nodeKeyMap;
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree)
=> _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap);
public SyntaxNodeKey GetNodeKey(SyntaxNode node)
{
var nodeKey = TryGetNodeKey(node);
if (nodeKey.IsEmpty)
{
throw new ArgumentException();
}
return nodeKey;
}
public SyntaxNodeKey TryGetNodeKey(SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree);
if (!nodeKeyMap.TryGetKey(node, out var nodeKey))
{
return SyntaxNodeKey.Empty;
}
return nodeKey;
}
public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
if (!nodeKeyMap.TryGetValue(nodeKey, out var node))
{
throw new ArgumentException();
}
return node;
}
public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
return nodeKeyMap.TryGetValue(nodeKey, out node);
}
public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree)
=> GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true);
protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container)
=> GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false);
public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container)
=> GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true);
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendant members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes);
public abstract string Language { get; }
public abstract string AssemblyAttributeString { get; }
public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol);
case SymbolKind.Field:
return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol);
case SymbolKind.Method:
return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol);
case SymbolKind.Namespace:
return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol);
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)symbol;
switch (namedType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Module:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType);
case TypeKind.Delegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType);
case TypeKind.Enum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType);
case TypeKind.Interface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType);
case TypeKind.Struct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType);
default:
throw Exceptions.ThrowEFail();
}
case SymbolKind.Property:
var propertySymbol = (IPropertySymbol)symbol;
return propertySymbol.IsWithEvents
? (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, propertySymbol)
: (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol);
default:
throw Exceptions.ThrowEFail();
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public abstract EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node);
public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Pointer ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.TypeKind == TypeKind.Submission)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return ExternalCodeUnknown.Create(state, projectId, typeSymbol);
}
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Dynamic)
{
var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object);
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj);
}
if (TryGetElementFromSource(state, project, typeSymbol, out var element))
{
return element;
}
var elementKind = GetElementKind(typeSymbol);
switch (elementKind)
{
case EnvDTE.vsCMElement.vsCMElementClass:
case EnvDTE.vsCMElement.vsCMElementModule:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementInterface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementDelegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementEnum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementStruct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol);
default:
Debug.Fail("Unsupported element kind: " + elementKind);
throw Exceptions.ThrowEInvalidArg();
}
}
public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract bool IsParameterNode(SyntaxNode node);
public abstract bool IsAttributeNode(SyntaxNode node);
public abstract bool IsAttributeArgumentNode(SyntaxNode node);
public abstract bool IsOptionNode(SyntaxNode node);
public abstract bool IsImportNode(SyntaxNode node);
public ISymbol ResolveSymbol(Microsoft.CodeAnalysis.Workspace workspace, ProjectId projectId, SymbolKey symbolId)
{
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol;
}
protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
var accessorKind = GetAccessorKind(node);
return CodeAccessorFunction.Create(state, parentObj, accessorKind);
}
protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = GetEffectiveParentForAttribute(node);
AbstractCodeElement parentObject;
if (IsParameterNode(parentNode))
{
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
else
{
var nodeKey = parentNode.AncestorsAndSelf()
.Select(n => TryGetNodeKey(n))
.FirstOrDefault(nk => nk != SyntaxNodeKey.Empty);
if (nodeKey == SyntaxNodeKey.Empty)
{
// This is an assembly-level attribute.
parentNode = fileCodeModel.GetSyntaxRoot();
parentObject = null;
}
else
{
parentNode = fileCodeModel.LookupNode(nodeKey);
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
}
GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal);
}
protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetImportParentAndName(node, out var parentNode, out var name);
AbstractCodeElement parentObj = null;
if (parentNode != null)
{
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent);
}
return CodeImport.Create(state, fileCodeModel, parentObj, name);
}
protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var name = GetParameterName(node);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeParameter.Create(state, parentObj, name);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetOptionNameAndOrdinal(node.Parent, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
GetInheritsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
GetImplementsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetAttributeArgumentParentAndIndex(node, out var attributeNode, out var index);
var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode);
var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute);
return CodeAttributeArgument.Create(state, codeAttributeObj, index);
}
public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
public abstract string GetUnescapedName(string name);
public abstract string GetName(SyntaxNode node);
public abstract SyntaxNode GetNodeWithName(SyntaxNode node);
public abstract SyntaxNode SetName(SyntaxNode node, string name);
public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
public void Rename(ISymbol symbol, string newName, Workspace workspace, ProjectCodeModelFactory projectCodeModelFactory)
{
// Save the node keys.
var nodeKeyValidation = new NodeKeyValidation(projectCodeModelFactory);
// Rename symbol.
var oldSolution = workspace.CurrentSolution;
// RenameSymbolAsync may be implemented using OOP, which has known cases for requiring the UI thread to do work. Use JTF
// to keep the rename action from deadlocking.
var newSolution = _threadingContext.JoinableTaskFactory.Run(() => Renamer.RenameSymbolAsync(oldSolution, symbol, newName, oldSolution.Options));
var changedDocuments = newSolution.GetChangedDocuments(oldSolution);
// Notify third parties of the coming rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
// Update the workspace.
if (!workspace.TryApplyChanges(newSolution))
{
throw Exceptions.ThrowEFail();
}
// Notify third parties of the completed rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
// Update the node keys.
nodeKeyValidation.RestoreKeys();
}
public abstract bool IsValidExternalSymbol(ISymbol symbol);
public abstract string GetExternalSymbolName(ISymbol symbol);
public abstract string GetExternalSymbolFullName(ISymbol symbol);
public VirtualTreePoint? GetStartPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part)
=> _nodeLocator.GetStartPoint(node, options, part);
public VirtualTreePoint? GetEndPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part)
=> _nodeLocator.GetEndPoint(node, options, part);
public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node);
public abstract SyntaxNode GetNodeWithType(SyntaxNode node);
public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node);
public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol)
{
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Class:
return EnvDTE.vsCMElement.vsCMElementClass;
case TypeKind.Interface:
return EnvDTE.vsCMElement.vsCMElementInterface;
case TypeKind.Struct:
return EnvDTE.vsCMElement.vsCMElementStruct;
case TypeKind.Enum:
return EnvDTE.vsCMElement.vsCMElementEnum;
case TypeKind.Delegate:
return EnvDTE.vsCMElement.vsCMElementDelegate;
case TypeKind.Module:
return EnvDTE.vsCMElement.vsCMElementModule;
default:
Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind);
throw Exceptions.ThrowEInvalidArg();
}
}
protected bool TryGetElementFromSource(
CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element)
{
element = null;
if (!typeSymbol.IsDefinition)
{
return false;
}
// Here's the strategy for determine what source file we'd try to return an element from.
// 1. Prefer source files that we don't heuristically flag as generated code.
// 2. If all of the source files are generated code, pick the first one.
Tuple<DocumentId, Location> generatedCode = null;
DocumentId chosenDocumentId = null;
Location chosenLocation = null;
foreach (var location in typeSymbol.Locations)
{
if (location.IsInSource)
{
var document = project.GetDocument(location.SourceTree);
if (document is null)
continue;
if (!document.IsGeneratedCode(CancellationToken.None))
{
chosenLocation = location;
chosenDocumentId = document.Id;
break;
}
else
{
generatedCode ??= Tuple.Create(document.Id, location);
}
}
}
if (chosenDocumentId == null && generatedCode != null)
{
chosenDocumentId = generatedCode.Item1;
chosenLocation = generatedCode.Item2;
}
if (chosenDocumentId != null)
{
var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId);
if (fileCodeModel != null)
{
var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel);
element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol));
return element != null;
}
}
return false;
}
public abstract bool IsExpressionBodiedProperty(SyntaxNode node);
public abstract bool IsAccessorNode(SyntaxNode node);
public abstract MethodKind GetAccessorKind(SyntaxNode node);
public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
public abstract bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode accessorNode);
public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
public abstract string GetAttributeTarget(SyntaxNode attributeNode);
public abstract string GetAttributeValue(SyntaxNode attributeNode);
public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node);
public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null);
public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value);
public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
public abstract string GetImportAlias(SyntaxNode node);
public abstract string GetImportNamespaceOrType(SyntaxNode node);
public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name);
public abstract SyntaxNode CreateImportNode(string name, string alias = null);
public abstract string GetParameterName(SyntaxNode node);
public virtual string GetParameterFullName(SyntaxNode node)
=> GetParameterName(node);
public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
public abstract EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode);
public abstract SyntaxNode CreateParameterNode(string name, string type);
public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
public abstract bool SupportsEventThrower { get; }
public abstract bool GetCanOverride(SyntaxNode memberNode);
public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
public abstract string GetComment(SyntaxNode node);
public abstract SyntaxNode SetComment(SyntaxNode node, string value);
public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
public abstract string GetDocComment(SyntaxNode node);
public abstract SyntaxNode SetDocComment(SyntaxNode node, string value);
public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind);
public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
public abstract bool GetIsConstant(SyntaxNode variableNode);
public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value);
public abstract bool GetIsDefault(SyntaxNode propertyNode);
public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
public abstract bool GetIsGeneric(SyntaxNode memberNode);
public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
public abstract bool GetMustImplement(SyntaxNode memberNode);
public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract Document Delete(Document document, SyntaxNode node);
public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetInitExpression(SyntaxNode node);
public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value);
public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode);
protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination);
public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
{
// Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive"
// Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8)
// We therefore check for this first.
if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
{
return Accessibility.ProtectedOrInternal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0)
{
return Accessibility.Private;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0)
{
return Accessibility.Internal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0)
{
return Accessibility.Protected;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0)
{
return Accessibility.Public;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0)
{
return GetDefaultAccessibility(targetSymbolKind, destination);
}
else
{
throw new ArgumentException(ServicesVSResources.Invalid_access, nameof(access));
}
}
public bool GetWithEvents(EnvDTE.vsCMAccess access)
=> (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0;
// TODO(DustinCa): Verify this list against VB
protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type)
=> type switch
{
EnvDTE.vsCMTypeRef.vsCMTypeRefBool => SpecialType.System_Boolean,
EnvDTE.vsCMTypeRef.vsCMTypeRefByte => SpecialType.System_Byte,
EnvDTE.vsCMTypeRef.vsCMTypeRefChar => SpecialType.System_Char,
EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal => SpecialType.System_Decimal,
EnvDTE.vsCMTypeRef.vsCMTypeRefDouble => SpecialType.System_Double,
EnvDTE.vsCMTypeRef.vsCMTypeRefFloat => SpecialType.System_Single,
EnvDTE.vsCMTypeRef.vsCMTypeRefInt => SpecialType.System_Int32,
EnvDTE.vsCMTypeRef.vsCMTypeRefLong => SpecialType.System_Int64,
EnvDTE.vsCMTypeRef.vsCMTypeRefObject => SpecialType.System_Object,
EnvDTE.vsCMTypeRef.vsCMTypeRefShort => SpecialType.System_Int16,
EnvDTE.vsCMTypeRef.vsCMTypeRefString => SpecialType.System_String,
EnvDTE.vsCMTypeRef.vsCMTypeRefVoid => SpecialType.System_Void,
_ => throw new ArgumentException(),
};
private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation)
=> compilation.GetSpecialType(GetSpecialType(type));
protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position);
public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position)
{
if (type is EnvDTE.CodeTypeRef)
{
return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position);
}
else if (type is EnvDTE.CodeType)
{
return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation);
}
ITypeSymbol typeSymbol;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation);
}
else if (type is string s)
{
typeSymbol = GetTypeSymbolFromPartialName(s, semanticModel, position);
}
else
{
throw new InvalidOperationException();
}
if (typeSymbol == null)
{
throw new ArgumentException();
}
return typeSymbol;
}
public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
protected abstract int GetAttributeIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified attribute.
/// </summary>
public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeIndexInContainer,
GetAttributeNodes);
}
protected abstract int GetAttributeArgumentIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeArgumentIndexInContainer,
GetAttributeArgumentNodes);
}
protected abstract int GetImportIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetImportIndexInContainer,
GetImportNodes);
}
protected abstract int GetParameterIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetParameterIndexInContainer,
GetParameterNodes);
}
/// <summary>
/// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true.
/// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found.
/// </summary>
protected abstract int GetMemberIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified member.
/// </summary>
public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetMemberIndexInContainer,
n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false));
}
private int PositionVariantToInsertionIndex(
object position,
SyntaxNode containerNode,
FileCodeModel fileCodeModel,
Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer,
Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes)
{
int result;
if (position is int i)
{
result = i;
}
else if (position is EnvDTE.CodeElement)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position);
if (codeElement == null || codeElement.FileCodeModel != fileCodeModel)
{
throw Exceptions.ThrowEInvalidArg();
}
var positionNode = codeElement.LookupNode();
if (positionNode == null)
{
throw Exceptions.ThrowEFail();
}
result = getIndexInContainer(containerNode, child => child == positionNode);
}
else if (position is string name)
{
result = getIndexInContainer(containerNode, child => GetName(child) == name);
}
else if (position == null || position == Type.Missing)
{
result = 0;
}
else
{
// Nothing we can handle...
throw Exceptions.ThrowEInvalidArg();
}
// -1 means to insert at the end, so we'll return the last child.
return result == -1
? getChildNodes(containerNode).ToArray().Length
: result;
}
protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode);
protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode);
protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode);
protected void GetNodesAroundInsertionIndex<TSyntaxNode>(
TSyntaxNode containerNode,
int childIndexToInsertAfter,
out TSyntaxNode insertBeforeNode,
out TSyntaxNode insertAfterNode)
where TSyntaxNode : SyntaxNode
{
var childNodes = GetLogicalMemberNodes(containerNode).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length);
// Initialize the nodes that we'll insert the new member before and after.
insertBeforeNode = null;
insertAfterNode = null;
if (childIndexToInsertAfter == 0)
{
if (childNodes.Length > 0)
{
insertBeforeNode = (TSyntaxNode)childNodes[0];
}
}
else
{
insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1];
if (childIndexToInsertAfter < childNodes.Length)
{
insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter];
}
}
if (insertBeforeNode != null)
{
insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode);
}
if (insertAfterNode != null)
{
insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode);
}
}
private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex)
{
var childNodes = GetLogicalMemberNodes(container).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length);
if (insertionIndex == 0)
{
return 0;
}
else
{
var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]);
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1;
}
}
private int GetAttributeArgumentInsertionIndex(int insertionIndex)
=> insertionIndex;
private int GetAttributeInsertionIndex(int insertionIndex)
=> insertionIndex;
private int GetImportInsertionIndex(int insertionIndex)
=> insertionIndex;
private int GetParameterInsertionIndex(int insertionIndex)
=> insertionIndex;
protected abstract bool IsCodeModelNode(SyntaxNode node);
protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span);
protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container);
protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container);
protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container);
private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<AbstractFormattingRule> additionalRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode();
var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan);
var formattingRules = Formatter.GetDefaultFormattingRules(document);
if (additionalRules != null)
{
formattingRules = additionalRules.Concat(formattingRules);
}
return _threadingContext.JoinableTaskFactory.Run(() => Formatter.FormatAsync(
document,
new TextSpan[] { formattingSpan },
options: null,
rules: formattingRules,
cancellationToken: cancellationToken));
}
private SyntaxNode InsertNode(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode node,
Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer,
CancellationToken cancellationToken,
out Document newDocument)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
var gen = SyntaxGenerator.GetGenerator(document);
node = node.WithAdditionalAnnotations(annotation);
if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport)
{
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
node = node.WithAdditionalAnnotations(Simplifier.Annotation);
}
var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode);
var newRoot = root.ReplaceNode(containerNode, newContainerNode);
document = document.WithSyntaxRoot(newRoot);
if (!batchMode)
{
document = _threadingContext.JoinableTaskFactory.Run(() =>
Simplifier.ReduceAsync(
document,
annotation,
optionSet: null,
cancellationToken: cancellationToken)
);
}
document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken);
// out param
newDocument = document;
// new node
return document
.GetSyntaxRootSynchronously(cancellationToken)
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode();
}
/// <summary>
/// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>.
/// This is used to determine whether a blank line should be added inside the body when formatting.
/// </summary>
protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode);
public Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken)
{
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var oldRoot = document.GetSyntaxRootSynchronously(cancellationToken);
var newRoot = oldRoot.ReplaceNode(node, annotatedNode);
document = document.WithSyntaxRoot(newRoot);
var additionalRules = AddBlankLineToMethodBody(node, newNode)
? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule)
: null;
document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken);
return document;
}
public SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeInsertionIndex(insertionIndex),
containerNode,
attributeNode,
InsertAttributeListIntoContainer,
cancellationToken,
out newDocument);
return GetAttributeFromAttributeDeclarationNode(finalNode);
}
public SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeArgumentInsertionIndex(insertionIndex),
containerNode,
attributeArgumentNode,
InsertAttributeArgumentIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetImportInsertionIndex(insertionIndex),
containerNode,
importNode,
InsertImportIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetParameterInsertionIndex(insertionIndex),
containerNode,
parameterNode,
InsertParameterIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode memberNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetMemberInsertionIndex(containerNode, insertionIndex),
containerNode,
memberNode,
InsertMemberNodeIntoContainer,
cancellationToken,
out newDocument);
return GetVariableFromFieldNode(finalNode);
}
public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree)
=> _eventCollector.Collect(oldTree, newTree);
public abstract bool IsNamespace(SyntaxNode node);
public abstract bool IsType(SyntaxNode node);
public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return SpecializedCollections.EmptyList<string>();
}
public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return false;
}
public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public abstract string[] GetFunctionExtenderNames();
public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetPropertyExtenderNames();
public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetExternalTypeExtenderNames();
public abstract object GetExternalTypeExtender(string name, string externalLocation);
public abstract string[] GetTypeExtenderNames();
public abstract object GetTypeExtender(string name, AbstractCodeType codeType);
public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void EnsureBufferFormatted(ITextBuffer buffer)
{
// can be override by languages if needed
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeGeneration;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.Formatting.Rules;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.LanguageServices;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Rename;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Simplification;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements;
using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Interop;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Editor.OptionsExtensionMethods;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel
{
internal abstract partial class AbstractCodeModelService : ICodeModelService
{
private readonly ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>> _treeToNodeKeyMaps =
new ConditionalWeakTable<SyntaxTree, IBidirectionalMap<SyntaxNodeKey, SyntaxNode>>();
protected readonly ISyntaxFactsService SyntaxFactsService;
private readonly IEditorOptionsFactoryService _editorOptionsFactoryService;
private readonly AbstractNodeNameGenerator _nodeNameGenerator;
private readonly AbstractNodeLocator _nodeLocator;
private readonly AbstractCodeModelEventCollector _eventCollector;
private readonly IEnumerable<IRefactorNotifyService> _refactorNotifyServices;
private readonly AbstractFormattingRule _lineAdjustmentFormattingRule;
private readonly AbstractFormattingRule _endRegionFormattingRule;
private readonly IThreadingContext _threadingContext;
protected AbstractCodeModelService(
HostLanguageServices languageServiceProvider,
IEditorOptionsFactoryService editorOptionsFactoryService,
IEnumerable<IRefactorNotifyService> refactorNotifyServices,
AbstractFormattingRule lineAdjustmentFormattingRule,
AbstractFormattingRule endRegionFormattingRule,
IThreadingContext threadingContext)
{
Debug.Assert(languageServiceProvider != null);
Debug.Assert(editorOptionsFactoryService != null);
this.SyntaxFactsService = languageServiceProvider.GetService<ISyntaxFactsService>();
_editorOptionsFactoryService = editorOptionsFactoryService;
_lineAdjustmentFormattingRule = lineAdjustmentFormattingRule;
_endRegionFormattingRule = endRegionFormattingRule;
_threadingContext = threadingContext;
_refactorNotifyServices = refactorNotifyServices;
_nodeNameGenerator = CreateNodeNameGenerator();
_nodeLocator = CreateNodeLocator();
_eventCollector = CreateCodeModelEventCollector();
}
protected string GetNewLineCharacter(SourceText text)
=> _editorOptionsFactoryService.GetEditorOptions(text).GetNewLineCharacter();
protected SyntaxToken GetTokenWithoutAnnotation(SyntaxToken current, Func<SyntaxToken, SyntaxToken> nextTokenGetter)
{
while (current.ContainsAnnotations)
{
current = nextTokenGetter(current);
}
return current;
}
protected TextSpan GetEncompassingSpan(SyntaxNode root, SyntaxToken startToken, SyntaxToken endToken)
{
var startPosition = startToken.SpanStart;
var endPosition = endToken.RawKind == 0 ? root.Span.End : endToken.Span.End;
return TextSpan.FromBounds(startPosition, endPosition);
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> BuildNodeKeyMap(SyntaxTree syntaxTree)
{
var nameOrdinalMap = new Dictionary<string, int>();
var nodeKeyMap = BidirectionalMap<SyntaxNodeKey, SyntaxNode>.Empty;
foreach (var node in GetFlattenedMemberNodes(syntaxTree))
{
var name = _nodeNameGenerator.GenerateName(node);
if (!nameOrdinalMap.TryGetValue(name, out var ordinal))
{
ordinal = 0;
}
nameOrdinalMap[name] = ++ordinal;
var key = new SyntaxNodeKey(name, ordinal);
nodeKeyMap = nodeKeyMap.Add(key, node);
}
return nodeKeyMap;
}
private IBidirectionalMap<SyntaxNodeKey, SyntaxNode> GetNodeKeyMap(SyntaxTree syntaxTree)
=> _treeToNodeKeyMaps.GetValue(syntaxTree, BuildNodeKeyMap);
public SyntaxNodeKey GetNodeKey(SyntaxNode node)
{
var nodeKey = TryGetNodeKey(node);
if (nodeKey.IsEmpty)
{
throw new ArgumentException();
}
return nodeKey;
}
public SyntaxNodeKey TryGetNodeKey(SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(node.SyntaxTree);
if (!nodeKeyMap.TryGetKey(node, out var nodeKey))
{
return SyntaxNodeKey.Empty;
}
return nodeKey;
}
public SyntaxNode LookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
if (!nodeKeyMap.TryGetValue(nodeKey, out var node))
{
throw new ArgumentException();
}
return node;
}
public bool TryLookupNode(SyntaxNodeKey nodeKey, SyntaxTree syntaxTree, out SyntaxNode node)
{
var nodeKeyMap = GetNodeKeyMap(syntaxTree);
return nodeKeyMap.TryGetValue(nodeKey, out node);
}
public abstract bool MatchesScope(SyntaxNode node, EnvDTE.vsCMElement scope);
public abstract IEnumerable<SyntaxNode> GetOptionNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImportNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetAttributeArgumentNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetInheritsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetImplementsNodes(SyntaxNode parent);
public abstract IEnumerable<SyntaxNode> GetParameterNodes(SyntaxNode parent);
protected IEnumerable<SyntaxNode> GetFlattenedMemberNodes(SyntaxTree syntaxTree)
=> GetMemberNodes(syntaxTree.GetRoot(), includeSelf: true, recursive: true, logicalFields: true, onlySupportedNodes: true);
protected IEnumerable<SyntaxNode> GetLogicalMemberNodes(SyntaxNode container)
=> GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: false);
public IEnumerable<SyntaxNode> GetLogicalSupportedMemberNodes(SyntaxNode container)
=> GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: true, onlySupportedNodes: true);
/// <summary>
/// Retrieves the members of a specified <paramref name="container"/> node. The members that are
/// returned can be controlled by passing various parameters.
/// </summary>
/// <param name="container">The <see cref="SyntaxNode"/> from which to retrieve members.</param>
/// <param name="includeSelf">If true, the container is returned as well.</param>
/// <param name="recursive">If true, members are recursed to return descendant members as well
/// as immediate children. For example, a namespace would return the namespaces and types within.
/// However, if <paramref name="recursive"/> is true, members with the namespaces and types would
/// also be returned.</param>
/// <param name="logicalFields">If true, field declarations are broken into their respective declarators.
/// For example, the field "int x, y" would return two declarators, one for x and one for y in place
/// of the field.</param>
/// <param name="onlySupportedNodes">If true, only members supported by Code Model are returned.</param>
public abstract IEnumerable<SyntaxNode> GetMemberNodes(SyntaxNode container, bool includeSelf, bool recursive, bool logicalFields, bool onlySupportedNodes);
public abstract string Language { get; }
public abstract string AssemblyAttributeString { get; }
public EnvDTE.CodeElement CreateExternalCodeElement(CodeModelState state, ProjectId projectId, ISymbol symbol)
{
switch (symbol.Kind)
{
case SymbolKind.Event:
return (EnvDTE.CodeElement)ExternalCodeEvent.Create(state, projectId, (IEventSymbol)symbol);
case SymbolKind.Field:
return (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, (IFieldSymbol)symbol);
case SymbolKind.Method:
return (EnvDTE.CodeElement)ExternalCodeFunction.Create(state, projectId, (IMethodSymbol)symbol);
case SymbolKind.Namespace:
return (EnvDTE.CodeElement)ExternalCodeNamespace.Create(state, projectId, (INamespaceSymbol)symbol);
case SymbolKind.NamedType:
var namedType = (INamedTypeSymbol)symbol;
switch (namedType.TypeKind)
{
case TypeKind.Class:
case TypeKind.Module:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, namedType);
case TypeKind.Delegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, namedType);
case TypeKind.Enum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, namedType);
case TypeKind.Interface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, namedType);
case TypeKind.Struct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, namedType);
default:
throw Exceptions.ThrowEFail();
}
case SymbolKind.Property:
var propertySymbol = (IPropertySymbol)symbol;
return propertySymbol.IsWithEvents
? (EnvDTE.CodeElement)ExternalCodeVariable.Create(state, projectId, propertySymbol)
: (EnvDTE.CodeElement)ExternalCodeProperty.Create(state, projectId, (IPropertySymbol)symbol);
default:
throw Exceptions.ThrowEFail();
}
}
/// <summary>
/// Do not use this method directly! Instead, go through <see cref="FileCodeModel.GetOrCreateCodeElement{T}(SyntaxNode)"/>
/// </summary>
public abstract EnvDTE.CodeElement CreateInternalCodeElement(
CodeModelState state,
FileCodeModel fileCodeModel,
SyntaxNode node);
public EnvDTE.CodeElement CreateCodeType(CodeModelState state, ProjectId projectId, ITypeSymbol typeSymbol)
{
if (typeSymbol.TypeKind == TypeKind.Pointer ||
typeSymbol.TypeKind == TypeKind.TypeParameter ||
typeSymbol.TypeKind == TypeKind.Submission)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Error ||
typeSymbol.TypeKind == TypeKind.Unknown)
{
return ExternalCodeUnknown.Create(state, projectId, typeSymbol);
}
var project = state.Workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
if (typeSymbol.TypeKind == TypeKind.Dynamic)
{
var obj = project.GetCompilationAsync().Result.GetSpecialType(SpecialType.System_Object);
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, obj);
}
if (TryGetElementFromSource(state, project, typeSymbol, out var element))
{
return element;
}
var elementKind = GetElementKind(typeSymbol);
switch (elementKind)
{
case EnvDTE.vsCMElement.vsCMElementClass:
case EnvDTE.vsCMElement.vsCMElementModule:
return (EnvDTE.CodeElement)ExternalCodeClass.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementInterface:
return (EnvDTE.CodeElement)ExternalCodeInterface.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementDelegate:
return (EnvDTE.CodeElement)ExternalCodeDelegate.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementEnum:
return (EnvDTE.CodeElement)ExternalCodeEnum.Create(state, projectId, typeSymbol);
case EnvDTE.vsCMElement.vsCMElementStruct:
return (EnvDTE.CodeElement)ExternalCodeStruct.Create(state, projectId, typeSymbol);
default:
Debug.Fail("Unsupported element kind: " + elementKind);
throw Exceptions.ThrowEInvalidArg();
}
}
public abstract EnvDTE.CodeTypeRef CreateCodeTypeRef(CodeModelState state, ProjectId projectId, object type);
public abstract EnvDTE.vsCMTypeRef GetTypeKindForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsFullNameForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract string GetAsStringForCodeTypeRef(ITypeSymbol typeSymbol);
public abstract bool IsParameterNode(SyntaxNode node);
public abstract bool IsAttributeNode(SyntaxNode node);
public abstract bool IsAttributeArgumentNode(SyntaxNode node);
public abstract bool IsOptionNode(SyntaxNode node);
public abstract bool IsImportNode(SyntaxNode node);
public ISymbol ResolveSymbol(Microsoft.CodeAnalysis.Workspace workspace, ProjectId projectId, SymbolKey symbolId)
{
var project = workspace.CurrentSolution.GetProject(projectId);
if (project == null)
{
throw Exceptions.ThrowEFail();
}
return symbolId.Resolve(project.GetCompilationAsync().Result).Symbol;
}
protected EnvDTE.CodeFunction CreateInternalCodeAccessorFunction(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
var accessorKind = GetAccessorKind(node);
return CodeAccessorFunction.Create(state, parentObj, accessorKind);
}
protected EnvDTE.CodeAttribute CreateInternalCodeAttribute(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = GetEffectiveParentForAttribute(node);
AbstractCodeElement parentObject;
if (IsParameterNode(parentNode))
{
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
else
{
var nodeKey = parentNode.AncestorsAndSelf()
.Select(n => TryGetNodeKey(n))
.FirstOrDefault(nk => nk != SyntaxNodeKey.Empty);
if (nodeKey == SyntaxNodeKey.Empty)
{
// This is an assembly-level attribute.
parentNode = fileCodeModel.GetSyntaxRoot();
parentObject = null;
}
else
{
parentNode = fileCodeModel.LookupNode(nodeKey);
var parentElement = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObject = ComAggregate.GetManagedObject<AbstractCodeElement>(parentElement);
}
}
GetAttributeNameAndOrdinal(parentNode, node, out var name, out var ordinal);
return CodeAttribute.Create(state, fileCodeModel, parentObject, name, ordinal);
}
protected EnvDTE80.CodeImport CreateInternalCodeImport(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetImportParentAndName(node, out var parentNode, out var name);
AbstractCodeElement parentObj = null;
if (parentNode != null)
{
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
parentObj = ComAggregate.GetManagedObject<AbstractCodeElement>(parent);
}
return CodeImport.Create(state, fileCodeModel, parentObj, name);
}
protected EnvDTE.CodeParameter CreateInternalCodeParameter(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
var name = GetParameterName(node);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeParameter.Create(state, parentObj, name);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeOptionStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetOptionNameAndOrdinal(node.Parent, node, out var name, out var ordinal);
return CodeOptionsStatement.Create(state, fileCodeModel, name, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeInheritsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
GetInheritsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeInheritsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeElement2 CreateInternalCodeImplementsStatement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
var parentNode = node
.Ancestors()
.FirstOrDefault(n => TryGetNodeKey(n) != SyntaxNodeKey.Empty);
if (parentNode == null)
{
throw new InvalidOperationException();
}
GetImplementsNamespaceAndOrdinal(parentNode, node, out var namespaceName, out var ordinal);
var parent = fileCodeModel.GetOrCreateCodeElement<EnvDTE.CodeElement>(parentNode);
var parentObj = ComAggregate.GetManagedObject<AbstractCodeMember>(parent);
return CodeImplementsStatement.Create(state, parentObj, namespaceName, ordinal);
}
protected EnvDTE80.CodeAttributeArgument CreateInternalCodeAttributeArgument(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node)
{
GetAttributeArgumentParentAndIndex(node, out var attributeNode, out var index);
var codeAttribute = CreateInternalCodeAttribute(state, fileCodeModel, attributeNode);
var codeAttributeObj = ComAggregate.GetManagedObject<CodeAttribute>(codeAttribute);
return CodeAttributeArgument.Create(state, codeAttributeObj, index);
}
public abstract EnvDTE.CodeElement CreateUnknownCodeElement(CodeModelState state, FileCodeModel fileCodeModel, SyntaxNode node);
public abstract EnvDTE.CodeElement CreateUnknownRootNamespaceCodeElement(CodeModelState state, FileCodeModel fileCodeModel);
public abstract string GetUnescapedName(string name);
public abstract string GetName(SyntaxNode node);
public abstract SyntaxNode GetNodeWithName(SyntaxNode node);
public abstract SyntaxNode SetName(SyntaxNode node, string name);
public abstract string GetFullName(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetFullyQualifiedName(string name, int position, SemanticModel semanticModel);
public void Rename(ISymbol symbol, string newName, Workspace workspace, ProjectCodeModelFactory projectCodeModelFactory)
{
// Save the node keys.
var nodeKeyValidation = new NodeKeyValidation(projectCodeModelFactory);
// Rename symbol.
var oldSolution = workspace.CurrentSolution;
// RenameSymbolAsync may be implemented using OOP, which has known cases for requiring the UI thread to do work. Use JTF
// to keep the rename action from deadlocking.
var newSolution = _threadingContext.JoinableTaskFactory.Run(() => Renamer.RenameSymbolAsync(oldSolution, symbol, newName, oldSolution.Options));
var changedDocuments = newSolution.GetChangedDocuments(oldSolution);
// Notify third parties of the coming rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnBeforeGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
// Update the workspace.
if (!workspace.TryApplyChanges(newSolution))
{
throw Exceptions.ThrowEFail();
}
// Notify third parties of the completed rename operation and let exceptions propagate out
_refactorNotifyServices.TryOnAfterGlobalSymbolRenamed(workspace, changedDocuments, symbol, newName, throwOnFailure: true);
RenameTrackingDismisser.DismissRenameTracking(workspace, changedDocuments);
// Update the node keys.
nodeKeyValidation.RestoreKeys();
}
public abstract bool IsValidExternalSymbol(ISymbol symbol);
public abstract string GetExternalSymbolName(ISymbol symbol);
public abstract string GetExternalSymbolFullName(ISymbol symbol);
public VirtualTreePoint? GetStartPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part)
=> _nodeLocator.GetStartPoint(node, options, part);
public VirtualTreePoint? GetEndPoint(SyntaxNode node, OptionSet options, EnvDTE.vsCMPart? part)
=> _nodeLocator.GetEndPoint(node, options, part);
public abstract EnvDTE.vsCMAccess GetAccess(ISymbol symbol);
public abstract EnvDTE.vsCMAccess GetAccess(SyntaxNode node);
public abstract SyntaxNode GetNodeWithModifiers(SyntaxNode node);
public abstract SyntaxNode GetNodeWithType(SyntaxNode node);
public abstract SyntaxNode GetNodeWithInitializer(SyntaxNode node);
public abstract SyntaxNode SetAccess(SyntaxNode node, EnvDTE.vsCMAccess access);
public abstract EnvDTE.vsCMElement GetElementKind(SyntaxNode node);
protected EnvDTE.vsCMElement GetElementKind(ITypeSymbol typeSymbol)
{
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Class:
return EnvDTE.vsCMElement.vsCMElementClass;
case TypeKind.Interface:
return EnvDTE.vsCMElement.vsCMElementInterface;
case TypeKind.Struct:
return EnvDTE.vsCMElement.vsCMElementStruct;
case TypeKind.Enum:
return EnvDTE.vsCMElement.vsCMElementEnum;
case TypeKind.Delegate:
return EnvDTE.vsCMElement.vsCMElementDelegate;
case TypeKind.Module:
return EnvDTE.vsCMElement.vsCMElementModule;
default:
Debug.Fail("Unexpected TypeKind: " + typeSymbol.TypeKind);
throw Exceptions.ThrowEInvalidArg();
}
}
protected bool TryGetElementFromSource(
CodeModelState state, Project project, ITypeSymbol typeSymbol, out EnvDTE.CodeElement element)
{
element = null;
if (!typeSymbol.IsDefinition)
{
return false;
}
// Here's the strategy for determine what source file we'd try to return an element from.
// 1. Prefer source files that we don't heuristically flag as generated code.
// 2. If all of the source files are generated code, pick the first one.
Tuple<DocumentId, Location> generatedCode = null;
DocumentId chosenDocumentId = null;
Location chosenLocation = null;
foreach (var location in typeSymbol.Locations)
{
if (location.IsInSource)
{
var document = project.GetDocument(location.SourceTree);
if (document is null)
continue;
if (!document.IsGeneratedCode(CancellationToken.None))
{
chosenLocation = location;
chosenDocumentId = document.Id;
break;
}
else
{
generatedCode ??= Tuple.Create(document.Id, location);
}
}
}
if (chosenDocumentId == null && generatedCode != null)
{
chosenDocumentId = generatedCode.Item1;
chosenLocation = generatedCode.Item2;
}
if (chosenDocumentId != null)
{
var fileCodeModel = state.Workspace.GetFileCodeModel(chosenDocumentId);
if (fileCodeModel != null)
{
var underlyingFileCodeModel = ComAggregate.GetManagedObject<FileCodeModel>(fileCodeModel);
element = underlyingFileCodeModel.CodeElementFromPosition(chosenLocation.SourceSpan.Start, GetElementKind(typeSymbol));
return element != null;
}
}
return false;
}
public abstract bool IsExpressionBodiedProperty(SyntaxNode node);
public abstract bool IsAccessorNode(SyntaxNode node);
public abstract MethodKind GetAccessorKind(SyntaxNode node);
public abstract bool TryGetAccessorNode(SyntaxNode parentNode, MethodKind kind, out SyntaxNode accessorNode);
public abstract bool TryGetAutoPropertyExpressionBody(SyntaxNode parentNode, out SyntaxNode accessorNode);
public abstract bool TryGetParameterNode(SyntaxNode parentNode, string name, out SyntaxNode parameterNode);
public abstract bool TryGetImportNode(SyntaxNode parentNode, string dottedName, out SyntaxNode importNode);
public abstract bool TryGetOptionNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode optionNode);
public abstract bool TryGetInheritsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode inheritsNode);
public abstract bool TryGetImplementsNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode implementsNode);
public abstract bool TryGetAttributeNode(SyntaxNode parentNode, string name, int ordinal, out SyntaxNode attributeNode);
public abstract bool TryGetAttributeArgumentNode(SyntaxNode attributeNode, int index, out SyntaxNode attributeArgumentNode);
public abstract void GetOptionNameAndOrdinal(SyntaxNode parentNode, SyntaxNode optionNode, out string name, out int ordinal);
public abstract void GetInheritsNamespaceAndOrdinal(SyntaxNode inheritsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetImplementsNamespaceAndOrdinal(SyntaxNode implementsNode, SyntaxNode optionNode, out string namespaceName, out int ordinal);
public abstract void GetAttributeNameAndOrdinal(SyntaxNode parentNode, SyntaxNode attributeNode, out string name, out int ordinal);
public abstract SyntaxNode GetAttributeTargetNode(SyntaxNode attributeNode);
public abstract string GetAttributeTarget(SyntaxNode attributeNode);
public abstract string GetAttributeValue(SyntaxNode attributeNode);
public abstract SyntaxNode SetAttributeTarget(SyntaxNode attributeNode, string value);
public abstract SyntaxNode SetAttributeValue(SyntaxNode attributeNode, string value);
public abstract SyntaxNode GetNodeWithAttributes(SyntaxNode node);
public abstract SyntaxNode GetEffectiveParentForAttribute(SyntaxNode node);
public abstract SyntaxNode CreateAttributeNode(string name, string value, string target = null);
public abstract void GetAttributeArgumentParentAndIndex(SyntaxNode attributeArgumentNode, out SyntaxNode attributeNode, out int index);
public abstract SyntaxNode CreateAttributeArgumentNode(string name, string value);
public abstract string GetAttributeArgumentValue(SyntaxNode attributeArgumentNode);
public abstract string GetImportAlias(SyntaxNode node);
public abstract string GetImportNamespaceOrType(SyntaxNode node);
public abstract void GetImportParentAndName(SyntaxNode importNode, out SyntaxNode namespaceNode, out string name);
public abstract SyntaxNode CreateImportNode(string name, string alias = null);
public abstract string GetParameterName(SyntaxNode node);
public virtual string GetParameterFullName(SyntaxNode node)
=> GetParameterName(node);
public abstract EnvDTE80.vsCMParameterKind GetParameterKind(SyntaxNode node);
public abstract SyntaxNode SetParameterKind(SyntaxNode node, EnvDTE80.vsCMParameterKind kind);
public abstract EnvDTE80.vsCMParameterKind UpdateParameterKind(EnvDTE80.vsCMParameterKind parameterKind, PARAMETER_PASSING_MODE passingMode);
public abstract SyntaxNode CreateParameterNode(string name, string type);
public abstract EnvDTE.vsCMFunction ValidateFunctionKind(SyntaxNode containerNode, EnvDTE.vsCMFunction kind, string name);
public abstract bool SupportsEventThrower { get; }
public abstract bool GetCanOverride(SyntaxNode memberNode);
public abstract SyntaxNode SetCanOverride(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMClassKind GetClassKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetClassKind(SyntaxNode typeNode, EnvDTE80.vsCMClassKind kind);
public abstract string GetComment(SyntaxNode node);
public abstract SyntaxNode SetComment(SyntaxNode node, string value);
public abstract EnvDTE80.vsCMConstKind GetConstKind(SyntaxNode variableNode);
public abstract SyntaxNode SetConstKind(SyntaxNode variableNode, EnvDTE80.vsCMConstKind kind);
public abstract EnvDTE80.vsCMDataTypeKind GetDataTypeKind(SyntaxNode typeNode, INamedTypeSymbol symbol);
public abstract SyntaxNode SetDataTypeKind(SyntaxNode typeNode, EnvDTE80.vsCMDataTypeKind kind);
public abstract string GetDocComment(SyntaxNode node);
public abstract SyntaxNode SetDocComment(SyntaxNode node, string value);
public abstract EnvDTE.vsCMFunction GetFunctionKind(IMethodSymbol symbol);
public abstract EnvDTE80.vsCMInheritanceKind GetInheritanceKind(SyntaxNode typeNode, INamedTypeSymbol typeSymbol);
public abstract SyntaxNode SetInheritanceKind(SyntaxNode typeNode, EnvDTE80.vsCMInheritanceKind kind);
public abstract bool GetIsAbstract(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsAbstract(SyntaxNode memberNode, bool value);
public abstract bool GetIsConstant(SyntaxNode variableNode);
public abstract SyntaxNode SetIsConstant(SyntaxNode variableNode, bool value);
public abstract bool GetIsDefault(SyntaxNode propertyNode);
public abstract SyntaxNode SetIsDefault(SyntaxNode propertyNode, bool value);
public abstract bool GetIsGeneric(SyntaxNode memberNode);
public abstract bool GetIsPropertyStyleEvent(SyntaxNode eventNode);
public abstract bool GetIsShared(SyntaxNode memberNode, ISymbol symbol);
public abstract SyntaxNode SetIsShared(SyntaxNode memberNode, bool value);
public abstract bool GetMustImplement(SyntaxNode memberNode);
public abstract SyntaxNode SetMustImplement(SyntaxNode memberNode, bool value);
public abstract EnvDTE80.vsCMOverrideKind GetOverrideKind(SyntaxNode memberNode);
public abstract SyntaxNode SetOverrideKind(SyntaxNode memberNode, EnvDTE80.vsCMOverrideKind kind);
public abstract EnvDTE80.vsCMPropertyKind GetReadWrite(SyntaxNode memberNode);
public abstract SyntaxNode SetType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract Document Delete(Document document, SyntaxNode node);
public abstract string GetMethodXml(SyntaxNode node, SemanticModel semanticModel);
public abstract string GetInitExpression(SyntaxNode node);
public abstract SyntaxNode AddInitExpression(SyntaxNode node, string value);
public abstract CodeGenerationDestination GetDestination(SyntaxNode containerNode);
protected abstract Accessibility GetDefaultAccessibility(SymbolKind targetSymbolKind, CodeGenerationDestination destination);
public Accessibility GetAccessibility(EnvDTE.vsCMAccess access, SymbolKind targetSymbolKind, CodeGenerationDestination destination = CodeGenerationDestination.Unspecified)
{
// Note: Some EnvDTE.vsCMAccess members aren't "bitwise-mutually-exclusive"
// Specifically, vsCMAccessProjectOrProtected (12) is a combination of vsCMAccessProject (4) and vsCMAccessProtected (8)
// We therefore check for this first.
if ((access & EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected) == EnvDTE.vsCMAccess.vsCMAccessProjectOrProtected)
{
return Accessibility.ProtectedOrInternal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPrivate) != 0)
{
return Accessibility.Private;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProject) != 0)
{
return Accessibility.Internal;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessProtected) != 0)
{
return Accessibility.Protected;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessPublic) != 0)
{
return Accessibility.Public;
}
else if ((access & EnvDTE.vsCMAccess.vsCMAccessDefault) != 0)
{
return GetDefaultAccessibility(targetSymbolKind, destination);
}
else
{
throw new ArgumentException(ServicesVSResources.Invalid_access, nameof(access));
}
}
public bool GetWithEvents(EnvDTE.vsCMAccess access)
=> (access & EnvDTE.vsCMAccess.vsCMAccessWithEvents) != 0;
// TODO(DustinCa): Verify this list against VB
protected SpecialType GetSpecialType(EnvDTE.vsCMTypeRef type)
=> type switch
{
EnvDTE.vsCMTypeRef.vsCMTypeRefBool => SpecialType.System_Boolean,
EnvDTE.vsCMTypeRef.vsCMTypeRefByte => SpecialType.System_Byte,
EnvDTE.vsCMTypeRef.vsCMTypeRefChar => SpecialType.System_Char,
EnvDTE.vsCMTypeRef.vsCMTypeRefDecimal => SpecialType.System_Decimal,
EnvDTE.vsCMTypeRef.vsCMTypeRefDouble => SpecialType.System_Double,
EnvDTE.vsCMTypeRef.vsCMTypeRefFloat => SpecialType.System_Single,
EnvDTE.vsCMTypeRef.vsCMTypeRefInt => SpecialType.System_Int32,
EnvDTE.vsCMTypeRef.vsCMTypeRefLong => SpecialType.System_Int64,
EnvDTE.vsCMTypeRef.vsCMTypeRefObject => SpecialType.System_Object,
EnvDTE.vsCMTypeRef.vsCMTypeRefShort => SpecialType.System_Int16,
EnvDTE.vsCMTypeRef.vsCMTypeRefString => SpecialType.System_String,
EnvDTE.vsCMTypeRef.vsCMTypeRefVoid => SpecialType.System_Void,
_ => throw new ArgumentException(),
};
private ITypeSymbol GetSpecialType(EnvDTE.vsCMTypeRef type, Compilation compilation)
=> compilation.GetSpecialType(GetSpecialType(type));
protected abstract ITypeSymbol GetTypeSymbolFromPartialName(string partialName, SemanticModel semanticModel, int position);
public abstract ITypeSymbol GetTypeSymbolFromFullName(string fullName, Compilation compilation);
public ITypeSymbol GetTypeSymbol(object type, SemanticModel semanticModel, int position)
{
if (type is EnvDTE.CodeTypeRef)
{
return GetTypeSymbolFromPartialName(((EnvDTE.CodeTypeRef)type).AsString, semanticModel, position);
}
else if (type is EnvDTE.CodeType)
{
return GetTypeSymbolFromFullName(((EnvDTE.CodeType)type).FullName, semanticModel.Compilation);
}
ITypeSymbol typeSymbol;
if (type is EnvDTE.vsCMTypeRef || type is int)
{
typeSymbol = GetSpecialType((EnvDTE.vsCMTypeRef)type, semanticModel.Compilation);
}
else if (type is string s)
{
typeSymbol = GetTypeSymbolFromPartialName(s, semanticModel, position);
}
else
{
throw new InvalidOperationException();
}
if (typeSymbol == null)
{
throw new ArgumentException();
}
return typeSymbol;
}
public abstract SyntaxNode CreateReturnDefaultValueStatement(ITypeSymbol type);
protected abstract int GetAttributeIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified attribute.
/// </summary>
public int PositionVariantToAttributeInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeIndexInContainer,
GetAttributeNodes);
}
protected abstract int GetAttributeArgumentIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToAttributeArgumentInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetAttributeArgumentIndexInContainer,
GetAttributeArgumentNodes);
}
protected abstract int GetImportIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToImportInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetImportIndexInContainer,
GetImportNodes);
}
protected abstract int GetParameterIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
public int PositionVariantToParameterInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetParameterIndexInContainer,
GetParameterNodes);
}
/// <summary>
/// Finds the index of the first child within the container for which <paramref name="predicate"/> returns true.
/// Note that the result is a 1-based as that is what code model expects. Returns -1 if no match is found.
/// </summary>
protected abstract int GetMemberIndexInContainer(
SyntaxNode containerNode,
Func<SyntaxNode, bool> predicate);
/// <summary>
/// The position argument is a VARIANT which may be an EnvDTE.CodeElement, an int or a string
/// representing the name of a member. This function translates the argument and returns the
/// 1-based position of the specified member.
/// </summary>
public int PositionVariantToMemberInsertionIndex(object position, SyntaxNode containerNode, FileCodeModel fileCodeModel)
{
return PositionVariantToInsertionIndex(
position,
containerNode,
fileCodeModel,
GetMemberIndexInContainer,
n => GetMemberNodes(n, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false));
}
private int PositionVariantToInsertionIndex(
object position,
SyntaxNode containerNode,
FileCodeModel fileCodeModel,
Func<SyntaxNode, Func<SyntaxNode, bool>, int> getIndexInContainer,
Func<SyntaxNode, IEnumerable<SyntaxNode>> getChildNodes)
{
int result;
if (position is int i)
{
result = i;
}
else if (position is EnvDTE.CodeElement)
{
var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(position);
if (codeElement == null || codeElement.FileCodeModel != fileCodeModel)
{
throw Exceptions.ThrowEInvalidArg();
}
var positionNode = codeElement.LookupNode();
if (positionNode == null)
{
throw Exceptions.ThrowEFail();
}
result = getIndexInContainer(containerNode, child => child == positionNode);
}
else if (position is string name)
{
result = getIndexInContainer(containerNode, child => GetName(child) == name);
}
else if (position == null || position == Type.Missing)
{
result = 0;
}
else
{
// Nothing we can handle...
throw Exceptions.ThrowEInvalidArg();
}
// -1 means to insert at the end, so we'll return the last child.
return result == -1
? getChildNodes(containerNode).ToArray().Length
: result;
}
protected abstract SyntaxNode GetFieldFromVariableNode(SyntaxNode variableNode);
protected abstract SyntaxNode GetVariableFromFieldNode(SyntaxNode fieldNode);
protected abstract SyntaxNode GetAttributeFromAttributeDeclarationNode(SyntaxNode attributeDeclarationNode);
protected void GetNodesAroundInsertionIndex<TSyntaxNode>(
TSyntaxNode containerNode,
int childIndexToInsertAfter,
out TSyntaxNode insertBeforeNode,
out TSyntaxNode insertAfterNode)
where TSyntaxNode : SyntaxNode
{
var childNodes = GetLogicalMemberNodes(containerNode).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(childIndexToInsertAfter >= 0 && childIndexToInsertAfter <= childNodes.Length);
// Initialize the nodes that we'll insert the new member before and after.
insertBeforeNode = null;
insertAfterNode = null;
if (childIndexToInsertAfter == 0)
{
if (childNodes.Length > 0)
{
insertBeforeNode = (TSyntaxNode)childNodes[0];
}
}
else
{
insertAfterNode = (TSyntaxNode)childNodes[childIndexToInsertAfter - 1];
if (childIndexToInsertAfter < childNodes.Length)
{
insertBeforeNode = (TSyntaxNode)childNodes[childIndexToInsertAfter];
}
}
if (insertBeforeNode != null)
{
insertBeforeNode = (TSyntaxNode)GetFieldFromVariableNode(insertBeforeNode);
}
if (insertAfterNode != null)
{
insertAfterNode = (TSyntaxNode)GetFieldFromVariableNode(insertAfterNode);
}
}
private int GetMemberInsertionIndex(SyntaxNode container, int insertionIndex)
{
var childNodes = GetLogicalMemberNodes(container).ToArray();
// Note: childIndexToInsertAfter is 1-based but can be 0, meaning insert before any other members.
// If it isn't 0, it means to insert the member node *after* the node at the 1-based index.
Debug.Assert(insertionIndex >= 0 && insertionIndex <= childNodes.Length);
if (insertionIndex == 0)
{
return 0;
}
else
{
var nodeAtIndex = GetFieldFromVariableNode(childNodes[insertionIndex - 1]);
return GetMemberNodes(container, includeSelf: false, recursive: false, logicalFields: false, onlySupportedNodes: false).ToList().IndexOf(nodeAtIndex) + 1;
}
}
private int GetAttributeArgumentInsertionIndex(int insertionIndex)
=> insertionIndex;
private int GetAttributeInsertionIndex(int insertionIndex)
=> insertionIndex;
private int GetImportInsertionIndex(int insertionIndex)
=> insertionIndex;
private int GetParameterInsertionIndex(int insertionIndex)
=> insertionIndex;
protected abstract bool IsCodeModelNode(SyntaxNode node);
protected abstract TextSpan GetSpanToFormat(SyntaxNode root, TextSpan span);
protected abstract SyntaxNode InsertMemberNodeIntoContainer(int index, SyntaxNode member, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeArgumentIntoContainer(int index, SyntaxNode attributeArgument, SyntaxNode container);
protected abstract SyntaxNode InsertAttributeListIntoContainer(int index, SyntaxNode attribute, SyntaxNode container);
protected abstract SyntaxNode InsertImportIntoContainer(int index, SyntaxNode import, SyntaxNode container);
protected abstract SyntaxNode InsertParameterIntoContainer(int index, SyntaxNode parameter, SyntaxNode container);
private Document FormatAnnotatedNode(Document document, SyntaxAnnotation annotation, IEnumerable<AbstractFormattingRule> additionalRules, CancellationToken cancellationToken)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
var annotatedNode = root.GetAnnotatedNodesAndTokens(annotation).Single().AsNode();
var formattingSpan = GetSpanToFormat(root, annotatedNode.FullSpan);
var formattingRules = Formatter.GetDefaultFormattingRules(document);
if (additionalRules != null)
{
formattingRules = additionalRules.Concat(formattingRules);
}
return _threadingContext.JoinableTaskFactory.Run(() => Formatter.FormatAsync(
document,
new TextSpan[] { formattingSpan },
options: null,
rules: formattingRules,
cancellationToken: cancellationToken));
}
private SyntaxNode InsertNode(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode node,
Func<int, SyntaxNode, SyntaxNode, SyntaxNode> insertNodeIntoContainer,
CancellationToken cancellationToken,
out Document newDocument)
{
var root = document.GetSyntaxRootSynchronously(cancellationToken);
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
var gen = SyntaxGenerator.GetGenerator(document);
node = node.WithAdditionalAnnotations(annotation);
if (gen.GetDeclarationKind(node) != DeclarationKind.NamespaceImport)
{
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
node = node.WithAdditionalAnnotations(Simplifier.Annotation);
}
var newContainerNode = insertNodeIntoContainer(insertionIndex, node, containerNode);
var newRoot = root.ReplaceNode(containerNode, newContainerNode);
document = document.WithSyntaxRoot(newRoot);
if (!batchMode)
{
document = _threadingContext.JoinableTaskFactory.Run(() =>
Simplifier.ReduceAsync(
document,
annotation,
optionSet: null,
cancellationToken: cancellationToken)
);
}
document = FormatAnnotatedNode(document, annotation, new[] { _lineAdjustmentFormattingRule, _endRegionFormattingRule }, cancellationToken);
// out param
newDocument = document;
// new node
return document
.GetSyntaxRootSynchronously(cancellationToken)
.GetAnnotatedNodesAndTokens(annotation)
.Single()
.AsNode();
}
/// <summary>
/// Override to determine whether <param name="newNode"/> adds a method body to <param name="node"/>.
/// This is used to determine whether a blank line should be added inside the body when formatting.
/// </summary>
protected abstract bool AddBlankLineToMethodBody(SyntaxNode node, SyntaxNode newNode);
public Document UpdateNode(
Document document,
SyntaxNode node,
SyntaxNode newNode,
CancellationToken cancellationToken)
{
// Annotate the member we're inserting so we can get back to it.
var annotation = new SyntaxAnnotation();
// REVIEW: how simplifier ever worked for code model? nobody added simplifier.Annotation before?
var annotatedNode = newNode.WithAdditionalAnnotations(annotation, Simplifier.Annotation);
var oldRoot = document.GetSyntaxRootSynchronously(cancellationToken);
var newRoot = oldRoot.ReplaceNode(node, annotatedNode);
document = document.WithSyntaxRoot(newRoot);
var additionalRules = AddBlankLineToMethodBody(node, newNode)
? SpecializedCollections.SingletonEnumerable(_lineAdjustmentFormattingRule)
: null;
document = FormatAnnotatedNode(document, annotation, additionalRules, cancellationToken);
return document;
}
public SyntaxNode InsertAttribute(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeInsertionIndex(insertionIndex),
containerNode,
attributeNode,
InsertAttributeListIntoContainer,
cancellationToken,
out newDocument);
return GetAttributeFromAttributeDeclarationNode(finalNode);
}
public SyntaxNode InsertAttributeArgument(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode attributeArgumentNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetAttributeArgumentInsertionIndex(insertionIndex),
containerNode,
attributeArgumentNode,
InsertAttributeArgumentIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertImport(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode importNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetImportInsertionIndex(insertionIndex),
containerNode,
importNode,
InsertImportIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertParameter(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode parameterNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetParameterInsertionIndex(insertionIndex),
containerNode,
parameterNode,
InsertParameterIntoContainer,
cancellationToken,
out newDocument);
return finalNode;
}
public SyntaxNode InsertMember(
Document document,
bool batchMode,
int insertionIndex,
SyntaxNode containerNode,
SyntaxNode memberNode,
CancellationToken cancellationToken,
out Document newDocument)
{
var finalNode = InsertNode(
document,
batchMode,
GetMemberInsertionIndex(containerNode, insertionIndex),
containerNode,
memberNode,
InsertMemberNodeIntoContainer,
cancellationToken,
out newDocument);
return GetVariableFromFieldNode(finalNode);
}
public Queue<CodeModelEvent> CollectCodeModelEvents(SyntaxTree oldTree, SyntaxTree newTree)
=> _eventCollector.Collect(oldTree, newTree);
public abstract bool IsNamespace(SyntaxNode node);
public abstract bool IsType(SyntaxNode node);
public virtual IList<string> GetHandledEventNames(SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return SpecializedCollections.EmptyList<string>();
}
public virtual bool HandlesEvent(string eventName, SyntaxNode method, SemanticModel semanticModel)
{
// descendants may override (particularly VB).
return false;
}
public virtual Document AddHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public virtual Document RemoveHandlesClause(Document document, string eventName, SyntaxNode method, CancellationToken cancellationToken)
{
// descendants may override (particularly VB).
return document;
}
public abstract string[] GetFunctionExtenderNames();
public abstract object GetFunctionExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetPropertyExtenderNames();
public abstract object GetPropertyExtender(string name, SyntaxNode node, ISymbol symbol);
public abstract string[] GetExternalTypeExtenderNames();
public abstract object GetExternalTypeExtender(string name, string externalLocation);
public abstract string[] GetTypeExtenderNames();
public abstract object GetTypeExtender(string name, AbstractCodeType codeType);
public abstract bool IsValidBaseType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveBase(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract bool IsValidInterfaceType(SyntaxNode node, ITypeSymbol typeSymbol);
public abstract SyntaxNode AddImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel, int? position);
public abstract SyntaxNode RemoveImplementedInterface(SyntaxNode node, ITypeSymbol typeSymbol, SemanticModel semanticModel);
public abstract string GetPrototype(SyntaxNode node, ISymbol symbol, PrototypeFlags flags);
public virtual void AttachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void DetachFormatTrackingToBuffer(ITextBuffer buffer)
{
// can be override by languages if needed
}
public virtual void EnsureBufferFormatted(ITextBuffer buffer)
{
// can be override by languages if needed
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Analyzers/VisualBasic/Tests/UseObjectInitializer/UseObjectInitializerTests.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.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.UseObjectInitializer
Public Class UseObjectInitializerTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicUseObjectInitializerDiagnosticAnalyzer(),
New VisualBasicUseObjectInitializerCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestOnVariableDeclarator() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c = [||]New C()
c.i = 1
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c = New C With {
.i = 1
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestOnVariableDeclarator2() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c As [||]New C()
c.i = 1
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c As New C With {
.i = 1
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestOnAssignmentExpression() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c as C = Nothing
c = [||]New C()
c.i = 1
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c as C = Nothing
c = New C With {
.i = 1
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestStopOnDuplicateMember() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c = [||]New C()
c.i = 1
c.i = 2
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c = New C With {
.i = 1
}
c.i = 2
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestComplexInitializer() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = [||]New C()
array(0).i = 1
array(0).j = 2
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = New C With {
.i = 1,
.j = 2
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestNotOnCompoundAssignment() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = [||]New C()
c.i = 1
c.j += 1
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = New C With {
.i = 1
}
c.j += 1
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestMissingWithExistingInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = [||]New C() With {
.i = 1
}
c.j = 1
End Sub
End Class")
End Function
<WorkItem(15012, "https://github.com/dotnet/roslyn/issues/15012")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestMissingIfImplicitMemberAccessWouldChange() As Task
Await TestMissingInRegularAndScriptAsync(
"
Class C
Sub M()
With New String()
Dim x As ProcessStartInfo = [||]New ProcessStartInfo()
x.Arguments = .Length.ToString()
End With
End Sub
End Class")
End Function
<WorkItem(15012, "https://github.com/dotnet/roslyn/issues/15012")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestIfImplicitMemberAccessWouldNotChange() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Sub M()
Dim x As ProcessStartInfo = [||]New ProcessStartInfo()
x.Arguments = Sub()
With New String()
Dim a = .Length.ToString()
End With
End Sub()
End Sub
End Class",
"
Class C
Sub M()
Dim x As ProcessStartInfo = New ProcessStartInfo With {
.Arguments = Sub()
With New String()
Dim a = .Length.ToString()
End With
End Sub()
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestFixAllInDocument() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = {|FixAllInDocument:New|} C()
array(0).i = 1
array(0).j = 2
array(1) = New C()
array(1).i = 3
array(1).j = 4
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = New C With {
.i = 1,
.j = 2
}
array(1) = New C With {
.i = 3,
.j = 4
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestTrivia1() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = [||]New C()
c.i = 1 ' Goo
c.j = 2 ' Bar
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = New C With {
.i = 1, ' Goo
.j = 2 ' Bar
}
End Sub
End Class")
End Function
<WorkItem(15525, "https://github.com/dotnet/roslyn/issues/15525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestTrivia2() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Sub M()
Dim XmlAppConfigReader As [||]New XmlTextReader(Reader)
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
XmlAppConfigReader.DtdProcessing = DtdProcessing.Prohibit
XmlAppConfigReader.WhitespaceHandling = WhitespaceHandling.All
End Sub
End Class",
"
Class C
Sub M()
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
Dim XmlAppConfigReader As New XmlTextReader(Reader) With {
.DtdProcessing = DtdProcessing.Prohibit,
.WhitespaceHandling = WhitespaceHandling.All
}
End Sub
End Class")
End Function
<WorkItem(15525, "https://github.com/dotnet/roslyn/issues/15525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestTrivia3() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Sub M()
Dim XmlAppConfigReader As [||]New XmlTextReader(Reader)
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
XmlAppConfigReader.DtdProcessing = DtdProcessing.Prohibit
' Bar
XmlAppConfigReader.WhitespaceHandling = WhitespaceHandling.All
End Sub
End Class",
"
Class C
Sub M()
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
' Bar
Dim XmlAppConfigReader As New XmlTextReader(Reader) With {
.DtdProcessing = DtdProcessing.Prohibit,
.WhitespaceHandling = WhitespaceHandling.All
}
End Sub
End Class")
End Function
<WorkItem(401322, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=401322")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestSharedMember() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim x As Integer
Shared y As Integer
Sub M()
Dim z = [||]New C()
z.x = 1
z.y = 2
End Sub
End Class
",
"
Class C
Dim x As Integer
Shared y As Integer
Sub M()
Dim z = New C With {
.x = 1
}
z.y = 2
End Sub
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers1() As Task
Await TestMissingInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers2() As Task
Await TestMissingInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.Name = String.Empty
c.LastName = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers3() As Task
Await TestInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.LastName = String.Empty
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
",
"
class C
Sub Bar()
Dim c As IExample = New Goo With {
.LastName = String.Empty
}
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers4() As Task
Await TestInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.LastName = String.Empty
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property MyLastName As String Implements IExample.LastName
End Class
",
"
class C
Sub Bar()
Dim c As IExample = New Goo With {
.MyLastName = String.Empty
}
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property MyLastName As String Implements IExample.LastName
End Class
")
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.CodeFixes
Imports Microsoft.CodeAnalysis.Diagnostics
Imports Microsoft.CodeAnalysis.VisualBasic.UseObjectInitializer
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Diagnostics.UseObjectInitializer
Public Class UseObjectInitializerTests
Inherits AbstractVisualBasicDiagnosticProviderBasedUserDiagnosticTest
Friend Overrides Function CreateDiagnosticProviderAndFixer(workspace As Workspace) As (DiagnosticAnalyzer, CodeFixProvider)
Return (New VisualBasicUseObjectInitializerDiagnosticAnalyzer(),
New VisualBasicUseObjectInitializerCodeFixProvider())
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestOnVariableDeclarator() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c = [||]New C()
c.i = 1
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c = New C With {
.i = 1
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestOnVariableDeclarator2() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c As [||]New C()
c.i = 1
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c As New C With {
.i = 1
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestOnAssignmentExpression() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c as C = Nothing
c = [||]New C()
c.i = 1
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c as C = Nothing
c = New C With {
.i = 1
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestStopOnDuplicateMember() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Sub M()
Dim c = [||]New C()
c.i = 1
c.i = 2
End Sub
End Class",
"
Class C
Dim i As Integer
Sub M()
Dim c = New C With {
.i = 1
}
c.i = 2
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestComplexInitializer() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = [||]New C()
array(0).i = 1
array(0).j = 2
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = New C With {
.i = 1,
.j = 2
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestNotOnCompoundAssignment() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = [||]New C()
c.i = 1
c.j += 1
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = New C With {
.i = 1
}
c.j += 1
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestMissingWithExistingInitializer() As Task
Await TestMissingInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = [||]New C() With {
.i = 1
}
c.j = 1
End Sub
End Class")
End Function
<WorkItem(15012, "https://github.com/dotnet/roslyn/issues/15012")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestMissingIfImplicitMemberAccessWouldChange() As Task
Await TestMissingInRegularAndScriptAsync(
"
Class C
Sub M()
With New String()
Dim x As ProcessStartInfo = [||]New ProcessStartInfo()
x.Arguments = .Length.ToString()
End With
End Sub
End Class")
End Function
<WorkItem(15012, "https://github.com/dotnet/roslyn/issues/15012")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestIfImplicitMemberAccessWouldNotChange() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Sub M()
Dim x As ProcessStartInfo = [||]New ProcessStartInfo()
x.Arguments = Sub()
With New String()
Dim a = .Length.ToString()
End With
End Sub()
End Sub
End Class",
"
Class C
Sub M()
Dim x As ProcessStartInfo = New ProcessStartInfo With {
.Arguments = Sub()
With New String()
Dim a = .Length.ToString()
End With
End Sub()
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestFixAllInDocument() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = {|FixAllInDocument:New|} C()
array(0).i = 1
array(0).j = 2
array(1) = New C()
array(1).i = 3
array(1).j = 4
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim array As C()
array(0) = New C With {
.i = 1,
.j = 2
}
array(1) = New C With {
.i = 3,
.j = 4
}
End Sub
End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestTrivia1() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = [||]New C()
c.i = 1 ' Goo
c.j = 2 ' Bar
End Sub
End Class",
"
Class C
Dim i As Integer
Dim j As Integer
Sub M()
Dim c = New C With {
.i = 1, ' Goo
.j = 2 ' Bar
}
End Sub
End Class")
End Function
<WorkItem(15525, "https://github.com/dotnet/roslyn/issues/15525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestTrivia2() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Sub M()
Dim XmlAppConfigReader As [||]New XmlTextReader(Reader)
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
XmlAppConfigReader.DtdProcessing = DtdProcessing.Prohibit
XmlAppConfigReader.WhitespaceHandling = WhitespaceHandling.All
End Sub
End Class",
"
Class C
Sub M()
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
Dim XmlAppConfigReader As New XmlTextReader(Reader) With {
.DtdProcessing = DtdProcessing.Prohibit,
.WhitespaceHandling = WhitespaceHandling.All
}
End Sub
End Class")
End Function
<WorkItem(15525, "https://github.com/dotnet/roslyn/issues/15525")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestTrivia3() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Sub M()
Dim XmlAppConfigReader As [||]New XmlTextReader(Reader)
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
XmlAppConfigReader.DtdProcessing = DtdProcessing.Prohibit
' Bar
XmlAppConfigReader.WhitespaceHandling = WhitespaceHandling.All
End Sub
End Class",
"
Class C
Sub M()
' Required by Fxcop rule CA3054 - DoNotAllowDTDXmlTextReader
' Bar
Dim XmlAppConfigReader As New XmlTextReader(Reader) With {
.DtdProcessing = DtdProcessing.Prohibit,
.WhitespaceHandling = WhitespaceHandling.All
}
End Sub
End Class")
End Function
<WorkItem(401322, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=401322")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestSharedMember() As Task
Await TestInRegularAndScriptAsync(
"
Class C
Dim x As Integer
Shared y As Integer
Sub M()
Dim z = [||]New C()
z.x = 1
z.y = 2
End Sub
End Class
",
"
Class C
Dim x As Integer
Shared y As Integer
Sub M()
Dim z = New C With {
.x = 1
}
z.y = 2
End Sub
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers1() As Task
Await TestMissingInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers2() As Task
Await TestMissingInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.Name = String.Empty
c.LastName = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers3() As Task
Await TestInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.LastName = String.Empty
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
",
"
class C
Sub Bar()
Dim c As IExample = New Goo With {
.LastName = String.Empty
}
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property LastName As String Implements IExample.LastName
End Class
")
End Function
<WorkItem(23368, "https://github.com/dotnet/roslyn/issues/23368")>
<Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseObjectInitializer)>
Public Async Function TestWithExplicitImplementedInterfaceMembers4() As Task
Await TestInRegularAndScriptAsync(
"
class C
Sub Bar()
Dim c As IExample = [||]New Goo
c.LastName = String.Empty
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property MyLastName As String Implements IExample.LastName
End Class
",
"
class C
Sub Bar()
Dim c As IExample = New Goo With {
.MyLastName = String.Empty
}
c.Name = String.Empty
End Sub
End Class
Interface IExample
Property Name As String
Property LastName As String
End Interface
Class Goo
Implements IExample
Private Property Name As String Implements IExample.Name
Public Property MyLastName As String Implements IExample.LastName
End Class
")
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/Lsif/GeneratorTest/FoldingRangeTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServer.Protocol
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public NotInheritable Class FoldingRangeTests
Private Const TestProjectAssemblyName As String = "TestProject"
' Expected 'FoldingRangeKind' argument would likely change for some of the tests when
' https://github.com/dotnet/roslyn/projects/45#card-20049168 is implemented.
<Theory>
<InlineData("
class C{|foldingRange:
{
}|}", Nothing)>
<InlineData("
class C{|foldingRange:
{
void M(){|foldingRange:
{
for (int i = 0; i < 10; i++){|foldingRange:
{
M();
}|}
}|}
}|}", Nothing)>
<InlineData("
{|foldingRange:#region
#endregion|}", Nothing)>
<InlineData("
using {|foldingRange:System;
using System.Linq;|}", FoldingRangeKind.Imports)>
<InlineData("
using {|foldingRange:S = System.String;
using System.Linq;|}", FoldingRangeKind.Imports)>
<InlineData("
{|foldingRange:// Comment Line 1
// Comment Line 2|}", Nothing)>
Public Async Function TestFoldingRanges(code As String, rangeKind As FoldingRangeKind?) As Task
Using workspace = TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true">
<Document Name="A.cs" FilePath="Z:\A.cs">
<%= code %>
</Document>
</Project>
</Workspace>)
Dim annotatedLocations = AbstractLanguageServerProtocolTests.GetAnnotatedLocations(workspace, workspace.CurrentSolution)
Dim expectedRanges = annotatedLocations("foldingRange").Select(Function(location) CreateFoldingRange(rangeKind, location.Range)).OrderBy(Function(range) range.StartLine).ToArray()
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(workspace)
Dim actualRanges = lsif.GetFoldingRanges(document)
AbstractLanguageServerProtocolTests.AssertJsonEquals(expectedRanges, actualRanges)
End Using
End Function
Private Shared Function CreateFoldingRange(kind As FoldingRangeKind?, range As Range) As FoldingRange
Return New FoldingRange() With
{
.Kind = kind,
.StartCharacter = range.Start.Character,
.EndCharacter = range.End.Character,
.StartLine = range.Start.Line,
.EndLine = range.End.Line
}
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Imports Microsoft.CodeAnalysis.Test.Utilities
Imports Microsoft.VisualStudio.LanguageServer.Protocol
Imports Roslyn.Test.Utilities
Imports Roslyn.Utilities
Namespace Microsoft.CodeAnalysis.LanguageServerIndexFormat.Generator.UnitTests
<UseExportProvider>
Public NotInheritable Class FoldingRangeTests
Private Const TestProjectAssemblyName As String = "TestProject"
' Expected 'FoldingRangeKind' argument would likely change for some of the tests when
' https://github.com/dotnet/roslyn/projects/45#card-20049168 is implemented.
<Theory>
<InlineData("
class C{|foldingRange:
{
}|}", Nothing)>
<InlineData("
class C{|foldingRange:
{
void M(){|foldingRange:
{
for (int i = 0; i < 10; i++){|foldingRange:
{
M();
}|}
}|}
}|}", Nothing)>
<InlineData("
{|foldingRange:#region
#endregion|}", Nothing)>
<InlineData("
using {|foldingRange:System;
using System.Linq;|}", FoldingRangeKind.Imports)>
<InlineData("
using {|foldingRange:S = System.String;
using System.Linq;|}", FoldingRangeKind.Imports)>
<InlineData("
{|foldingRange:// Comment Line 1
// Comment Line 2|}", Nothing)>
Public Async Function TestFoldingRanges(code As String, rangeKind As FoldingRangeKind?) As Task
Using workspace = TestWorkspace.CreateWorkspace(
<Workspace>
<Project Language="C#" AssemblyName=<%= TestProjectAssemblyName %> FilePath="Z:\TestProject.csproj" CommonReferences="true">
<Document Name="A.cs" FilePath="Z:\A.cs">
<%= code %>
</Document>
</Project>
</Workspace>)
Dim annotatedLocations = AbstractLanguageServerProtocolTests.GetAnnotatedLocations(workspace, workspace.CurrentSolution)
Dim expectedRanges = annotatedLocations("foldingRange").Select(Function(location) CreateFoldingRange(rangeKind, location.Range)).OrderBy(Function(range) range.StartLine).ToArray()
Dim document = workspace.CurrentSolution.Projects.Single().Documents.Single()
Dim lsif = Await TestLsifOutput.GenerateForWorkspaceAsync(workspace)
Dim actualRanges = lsif.GetFoldingRanges(document)
AbstractLanguageServerProtocolTests.AssertJsonEquals(expectedRanges, actualRanges)
End Using
End Function
Private Shared Function CreateFoldingRange(kind As FoldingRangeKind?, range As Range) As FoldingRange
Return New FoldingRange() With
{
.Kind = kind,
.StartCharacter = range.Start.Character,
.EndCharacter = range.End.Character,
.StartLine = range.Start.Line,
.EndLine = range.End.Line
}
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Features/Core/Portable/FindUsages/DefinitionItem.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tags;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's definition that can be displayed in an editor
/// and used for navigation.
///
/// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create
/// overloads.
///
/// Subclassing is also supported for scenarios that fall outside the bounds of
/// these common cases.
/// </summary>
internal abstract partial class DefinitionItem
{
/// <summary>
/// The definition item corresponding to the initial symbol the user was trying to find. This item should get
/// prominent placement in the final UI for the user.
/// </summary>
internal const string Primary = nameof(Primary);
// Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One
// for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing
// on a constructor, then the fallback symbol will be the actual type that the constructor
// is contained within.
internal const string RQNameKey1 = nameof(RQNameKey1);
internal const string RQNameKey2 = nameof(RQNameKey2);
/// <summary>
/// For metadata symbols we encode information in the <see cref="Properties"/> so we can
/// retrieve the symbol later on when navigating. This is needed so that we can go to
/// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/>
/// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol.
/// </summary>
private const string MetadataSymbolKey = nameof(MetadataSymbolKey);
private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid);
private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName);
/// <summary>
/// If this item is something that cannot be navigated to. We store this in our
/// <see cref="Properties"/> to act as an explicit marker that navigation is not possible.
/// </summary>
private const string NonNavigable = nameof(NonNavigable);
/// <summary>
/// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the
/// item is displayed.
/// </summary>
public ImmutableArray<string> Tags { get; }
/// <summary>
/// Additional properties that can be attached to the definition for clients that want to
/// keep track of additional data.
/// </summary>
public ImmutableDictionary<string, string> Properties { get; }
/// <summary>
/// Additional diplayable properties that can be attached to the definition for clients that want to
/// display additional data.
/// </summary>
public ImmutableDictionary<string, string> DisplayableProperties { get; }
/// <summary>
/// The DisplayParts just for the name of this definition. Generally used only for
/// error messages.
/// </summary>
public ImmutableArray<TaggedText> NameDisplayParts { get; }
/// <summary>
/// The full display parts for this definition. Displayed in a classified
/// manner when possible.
/// </summary>
public ImmutableArray<TaggedText> DisplayParts { get; }
/// <summary>
/// Where the location originally came from (for example, the containing assembly or
/// project name). May be used in the presentation of a definition.
/// </summary>
public ImmutableArray<TaggedText> OriginationParts { get; }
/// <summary>
/// Additional locations to present in the UI. A definition may have multiple locations
/// for cases like partial types/members.
/// </summary>
public ImmutableArray<DocumentSpan> SourceSpans { get; }
/// <summary>
/// Whether or not this definition should be presented if we never found any references to
/// it. For example, when searching for a property, the FindReferences engine will cascade
/// to the accessors in case any code specifically called those accessors (can happen in
/// cross-language cases). However, in the normal case where there were no calls specifically
/// to the accessor, we would not want to display them in the UI.
///
/// For most definitions we will want to display them, even if no references were found.
/// This property allows for this customization in behavior.
/// </summary>
public bool DisplayIfNoReferences { get; }
internal abstract bool IsExternal { get; }
// F# uses this
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
bool displayIfNoReferences)
: this(
tags,
displayParts,
nameDisplayParts,
originationParts,
sourceSpans,
properties,
ImmutableDictionary<string, string>.Empty,
displayIfNoReferences)
{
}
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
ImmutableDictionary<string, string> displayableProperties,
bool displayIfNoReferences)
{
Tags = tags;
DisplayParts = displayParts;
NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts;
OriginationParts = originationParts.NullToEmpty();
SourceSpans = sourceSpans.NullToEmpty();
Properties = properties ?? ImmutableDictionary<string, string>.Empty;
DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty;
DisplayIfNoReferences = displayIfNoReferences;
if (Properties.ContainsKey(MetadataSymbolKey))
{
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid));
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName));
}
}
[Obsolete("Override CanNavigateToAsync instead", error: false)]
public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken);
[Obsolete("Override TryNavigateToAsync instead", error: false)]
public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken);
public virtual Task<bool> CanNavigateToAsync(Workspace workspace, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(CanNavigateTo(workspace, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public virtual Task<bool> TryNavigateToAsync(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(TryNavigateTo(workspace, showInPreviewTab, activateTab, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
DocumentSpan sourceSpan,
ImmutableArray<TaggedText> nameDisplayParts = default,
bool displayIfNoReferences = true)
{
return Create(
tags, displayParts, ImmutableArray.Create(sourceSpan),
nameDisplayParts, displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts,
bool displayIfNoReferences)
{
return Create(
tags, displayParts, sourceSpans, nameDisplayParts,
properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
ImmutableDictionary<string, string> displayableProperties = null,
bool displayIfNoReferences = true)
{
if (sourceSpans.Length == 0)
{
throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty.");
}
var firstDocument = sourceSpans[0].Document;
var originationParts = ImmutableArray.Create(
new TaggedText(TextTags.Text, firstDocument.Project.Name));
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans, properties, displayableProperties, displayIfNoReferences);
}
internal static DefinitionItem CreateMetadataDefinition(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
Solution solution,
ISymbol symbol,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
var symbolKey = symbol.GetSymbolKey().ToString();
var projectId = solution.GetOriginatingProjectId(symbol);
Contract.ThrowIfNull(projectId);
properties = properties.Add(MetadataSymbolKey, symbolKey)
.Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString())
.Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName);
var originationParts = GetOriginationParts(symbol);
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts,
bool displayIfNoReferences)
{
return CreateNonNavigableItem(
tags, displayParts, originationParts,
properties: null, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.Add(NonNavigable, "");
return new DefaultDefinitionItem(
tags: tags,
displayParts: displayParts,
nameDisplayParts: ImmutableArray<TaggedText>.Empty,
originationParts: originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol)
{
// We don't show an origination location for a namespace because it can span over
// both metadata assemblies and source projects.
//
// Otherwise show the assembly this symbol came from as the Origination of
// the DefinitionItem.
if (symbol.Kind != SymbolKind.Namespace)
{
var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
if (!string.IsNullOrWhiteSpace(assemblyName))
{
return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName));
}
}
return ImmutableArray<TaggedText>.Empty;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Tags;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.FindUsages
{
/// <summary>
/// Information about a symbol's definition that can be displayed in an editor
/// and used for navigation.
///
/// Standard implmentations can be obtained through the various <see cref="DefinitionItem"/>.Create
/// overloads.
///
/// Subclassing is also supported for scenarios that fall outside the bounds of
/// these common cases.
/// </summary>
internal abstract partial class DefinitionItem
{
/// <summary>
/// The definition item corresponding to the initial symbol the user was trying to find. This item should get
/// prominent placement in the final UI for the user.
/// </summary>
internal const string Primary = nameof(Primary);
// Existing behavior is to do up to two lookups for 3rd party navigation for FAR. One
// for the symbol itself and one for a 'fallback' symbol. For example, if we're FARing
// on a constructor, then the fallback symbol will be the actual type that the constructor
// is contained within.
internal const string RQNameKey1 = nameof(RQNameKey1);
internal const string RQNameKey2 = nameof(RQNameKey2);
/// <summary>
/// For metadata symbols we encode information in the <see cref="Properties"/> so we can
/// retrieve the symbol later on when navigating. This is needed so that we can go to
/// metadata-as-source for metadata symbols. We need to store the <see cref="SymbolKey"/>
/// for the symbol and the project ID that originated the symbol. With these we can correctly recover the symbol.
/// </summary>
private const string MetadataSymbolKey = nameof(MetadataSymbolKey);
private const string MetadataSymbolOriginatingProjectIdGuid = nameof(MetadataSymbolOriginatingProjectIdGuid);
private const string MetadataSymbolOriginatingProjectIdDebugName = nameof(MetadataSymbolOriginatingProjectIdDebugName);
/// <summary>
/// If this item is something that cannot be navigated to. We store this in our
/// <see cref="Properties"/> to act as an explicit marker that navigation is not possible.
/// </summary>
private const string NonNavigable = nameof(NonNavigable);
/// <summary>
/// Descriptive tags from <see cref="WellKnownTags"/>. These tags may influence how the
/// item is displayed.
/// </summary>
public ImmutableArray<string> Tags { get; }
/// <summary>
/// Additional properties that can be attached to the definition for clients that want to
/// keep track of additional data.
/// </summary>
public ImmutableDictionary<string, string> Properties { get; }
/// <summary>
/// Additional diplayable properties that can be attached to the definition for clients that want to
/// display additional data.
/// </summary>
public ImmutableDictionary<string, string> DisplayableProperties { get; }
/// <summary>
/// The DisplayParts just for the name of this definition. Generally used only for
/// error messages.
/// </summary>
public ImmutableArray<TaggedText> NameDisplayParts { get; }
/// <summary>
/// The full display parts for this definition. Displayed in a classified
/// manner when possible.
/// </summary>
public ImmutableArray<TaggedText> DisplayParts { get; }
/// <summary>
/// Where the location originally came from (for example, the containing assembly or
/// project name). May be used in the presentation of a definition.
/// </summary>
public ImmutableArray<TaggedText> OriginationParts { get; }
/// <summary>
/// Additional locations to present in the UI. A definition may have multiple locations
/// for cases like partial types/members.
/// </summary>
public ImmutableArray<DocumentSpan> SourceSpans { get; }
/// <summary>
/// Whether or not this definition should be presented if we never found any references to
/// it. For example, when searching for a property, the FindReferences engine will cascade
/// to the accessors in case any code specifically called those accessors (can happen in
/// cross-language cases). However, in the normal case where there were no calls specifically
/// to the accessor, we would not want to display them in the UI.
///
/// For most definitions we will want to display them, even if no references were found.
/// This property allows for this customization in behavior.
/// </summary>
public bool DisplayIfNoReferences { get; }
internal abstract bool IsExternal { get; }
// F# uses this
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
bool displayIfNoReferences)
: this(
tags,
displayParts,
nameDisplayParts,
originationParts,
sourceSpans,
properties,
ImmutableDictionary<string, string>.Empty,
displayIfNoReferences)
{
}
protected DefinitionItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
ImmutableArray<TaggedText> originationParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableDictionary<string, string> properties,
ImmutableDictionary<string, string> displayableProperties,
bool displayIfNoReferences)
{
Tags = tags;
DisplayParts = displayParts;
NameDisplayParts = nameDisplayParts.IsDefaultOrEmpty ? displayParts : nameDisplayParts;
OriginationParts = originationParts.NullToEmpty();
SourceSpans = sourceSpans.NullToEmpty();
Properties = properties ?? ImmutableDictionary<string, string>.Empty;
DisplayableProperties = displayableProperties ?? ImmutableDictionary<string, string>.Empty;
DisplayIfNoReferences = displayIfNoReferences;
if (Properties.ContainsKey(MetadataSymbolKey))
{
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdGuid));
Contract.ThrowIfFalse(Properties.ContainsKey(MetadataSymbolOriginatingProjectIdDebugName));
}
}
[Obsolete("Override CanNavigateToAsync instead", error: false)]
public abstract bool CanNavigateTo(Workspace workspace, CancellationToken cancellationToken);
[Obsolete("Override TryNavigateToAsync instead", error: false)]
public abstract bool TryNavigateTo(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken);
public virtual Task<bool> CanNavigateToAsync(Workspace workspace, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(CanNavigateTo(workspace, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public virtual Task<bool> TryNavigateToAsync(Workspace workspace, bool showInPreviewTab, bool activateTab, CancellationToken cancellationToken)
{
#pragma warning disable CS0618 // Type or member is obsolete
return Task.FromResult(TryNavigateTo(workspace, showInPreviewTab, activateTab, cancellationToken));
#pragma warning restore CS0618 // Type or member is obsolete
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
DocumentSpan sourceSpan,
ImmutableArray<TaggedText> nameDisplayParts = default,
bool displayIfNoReferences = true)
{
return Create(
tags, displayParts, ImmutableArray.Create(sourceSpan),
nameDisplayParts, displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts,
bool displayIfNoReferences)
{
return Create(
tags, displayParts, sourceSpans, nameDisplayParts,
properties: null, displayableProperties: ImmutableDictionary<string, string>.Empty, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
return Create(tags, displayParts, sourceSpans, nameDisplayParts, properties, ImmutableDictionary<string, string>.Empty, displayIfNoReferences);
}
public static DefinitionItem Create(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<DocumentSpan> sourceSpans,
ImmutableArray<TaggedText> nameDisplayParts = default,
ImmutableDictionary<string, string> properties = null,
ImmutableDictionary<string, string> displayableProperties = null,
bool displayIfNoReferences = true)
{
if (sourceSpans.Length == 0)
{
throw new ArgumentException($"{nameof(sourceSpans)} cannot be empty.");
}
var firstDocument = sourceSpans[0].Document;
var originationParts = ImmutableArray.Create(
new TaggedText(TextTags.Text, firstDocument.Project.Name));
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans, properties, displayableProperties, displayIfNoReferences);
}
internal static DefinitionItem CreateMetadataDefinition(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> nameDisplayParts,
Solution solution,
ISymbol symbol,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
var symbolKey = symbol.GetSymbolKey().ToString();
var projectId = solution.GetOriginatingProjectId(symbol);
Contract.ThrowIfNull(projectId);
properties = properties.Add(MetadataSymbolKey, symbolKey)
.Add(MetadataSymbolOriginatingProjectIdGuid, projectId.Id.ToString())
.Add(MetadataSymbolOriginatingProjectIdDebugName, projectId.DebugName);
var originationParts = GetOriginationParts(symbol);
return new DefaultDefinitionItem(
tags, displayParts, nameDisplayParts, originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
// Kept around for binary compat with F#/TypeScript.
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts,
bool displayIfNoReferences)
{
return CreateNonNavigableItem(
tags, displayParts, originationParts,
properties: null, displayIfNoReferences: displayIfNoReferences);
}
public static DefinitionItem CreateNonNavigableItem(
ImmutableArray<string> tags,
ImmutableArray<TaggedText> displayParts,
ImmutableArray<TaggedText> originationParts = default,
ImmutableDictionary<string, string> properties = null,
bool displayIfNoReferences = true)
{
properties ??= ImmutableDictionary<string, string>.Empty;
properties = properties.Add(NonNavigable, "");
return new DefaultDefinitionItem(
tags: tags,
displayParts: displayParts,
nameDisplayParts: ImmutableArray<TaggedText>.Empty,
originationParts: originationParts,
sourceSpans: ImmutableArray<DocumentSpan>.Empty,
properties: properties,
displayableProperties: ImmutableDictionary<string, string>.Empty,
displayIfNoReferences: displayIfNoReferences);
}
internal static ImmutableArray<TaggedText> GetOriginationParts(ISymbol symbol)
{
// We don't show an origination location for a namespace because it can span over
// both metadata assemblies and source projects.
//
// Otherwise show the assembly this symbol came from as the Origination of
// the DefinitionItem.
if (symbol.Kind != SymbolKind.Namespace)
{
var assemblyName = symbol.ContainingAssembly?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
if (!string.IsNullOrWhiteSpace(assemblyName))
{
return ImmutableArray.Create(new TaggedText(TextTags.Assembly, assemblyName));
}
}
return ImmutableArray<TaggedText>.Empty;
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/Core/Shared/Utilities/CaretPreservingEditTransaction.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
internal class CaretPreservingEditTransaction : IDisposable
{
private readonly IEditorOperations _editorOperations;
private readonly ITextUndoHistory? _undoHistory;
private ITextUndoTransaction? _transaction;
private bool _active;
public CaretPreservingEditTransaction(
string description,
ITextView textView,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: this(description, undoHistoryRegistry.GetHistory(textView.TextBuffer), editorOperationsFactoryService.GetEditorOperations(textView))
{
}
public CaretPreservingEditTransaction(string description, ITextUndoHistory? undoHistory, IEditorOperations editorOperations)
{
_editorOperations = editorOperations;
_undoHistory = undoHistory;
_active = true;
if (_undoHistory != null)
{
_transaction = new HACK_TextUndoTransactionThatRollsBackProperly(_undoHistory.CreateTransaction(description));
_editorOperations.AddBeforeTextBufferChangePrimitive();
}
}
public static CaretPreservingEditTransaction? TryCreate(string description,
ITextView textView,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
if (undoHistoryRegistry.TryGetHistory(textView.TextBuffer, out _))
{
return new CaretPreservingEditTransaction(description, textView, undoHistoryRegistry, editorOperationsFactoryService);
}
return null;
}
public void Complete()
{
if (!_active)
{
throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete);
}
_editorOperations.AddAfterTextBufferChangePrimitive();
if (_transaction != null)
{
_transaction.Complete();
}
EndTransaction();
}
public void Cancel()
{
if (!_active)
{
throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete);
}
if (_transaction != null)
{
_transaction.Cancel();
}
EndTransaction();
}
public void Dispose()
{
if (_transaction != null)
{
// If the transaction is still pending, we'll cancel it
Cancel();
}
}
public IMergeTextUndoTransactionPolicy? MergePolicy
{
get
{
return _transaction?.MergePolicy;
}
set
{
if (_transaction != null)
{
_transaction.MergePolicy = value;
}
}
}
private void EndTransaction()
{
if (_transaction != null)
{
_transaction.Dispose();
_transaction = null;
}
_active = false;
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Text.Operations;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
internal class CaretPreservingEditTransaction : IDisposable
{
private readonly IEditorOperations _editorOperations;
private readonly ITextUndoHistory? _undoHistory;
private ITextUndoTransaction? _transaction;
private bool _active;
public CaretPreservingEditTransaction(
string description,
ITextView textView,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
: this(description, undoHistoryRegistry.GetHistory(textView.TextBuffer), editorOperationsFactoryService.GetEditorOperations(textView))
{
}
public CaretPreservingEditTransaction(string description, ITextUndoHistory? undoHistory, IEditorOperations editorOperations)
{
_editorOperations = editorOperations;
_undoHistory = undoHistory;
_active = true;
if (_undoHistory != null)
{
_transaction = new HACK_TextUndoTransactionThatRollsBackProperly(_undoHistory.CreateTransaction(description));
_editorOperations.AddBeforeTextBufferChangePrimitive();
}
}
public static CaretPreservingEditTransaction? TryCreate(string description,
ITextView textView,
ITextUndoHistoryRegistry undoHistoryRegistry,
IEditorOperationsFactoryService editorOperationsFactoryService)
{
if (undoHistoryRegistry.TryGetHistory(textView.TextBuffer, out _))
{
return new CaretPreservingEditTransaction(description, textView, undoHistoryRegistry, editorOperationsFactoryService);
}
return null;
}
public void Complete()
{
if (!_active)
{
throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete);
}
_editorOperations.AddAfterTextBufferChangePrimitive();
if (_transaction != null)
{
_transaction.Complete();
}
EndTransaction();
}
public void Cancel()
{
if (!_active)
{
throw new InvalidOperationException(EditorFeaturesResources.The_transaction_is_already_complete);
}
if (_transaction != null)
{
_transaction.Cancel();
}
EndTransaction();
}
public void Dispose()
{
if (_transaction != null)
{
// If the transaction is still pending, we'll cancel it
Cancel();
}
}
public IMergeTextUndoTransactionPolicy? MergePolicy
{
get
{
return _transaction?.MergePolicy;
}
set
{
if (_transaction != null)
{
_transaction.MergePolicy = value;
}
}
}
private void EndTransaction()
{
if (_transaction != null)
{
_transaction.Dispose();
_transaction = null;
}
_active = false;
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/EditorFeatures/VisualBasicTest/BraceMatching/VisualBasicBraceMatcherTests.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Editor.UnitTests.BraceMatching
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching
Public Class VisualBasicBraceMatcherTests
Inherits AbstractBraceMatcherTests
Protected Overrides Function CreateWorkspaceFromCode(code As String, options As ParseOptions) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(code)
End Function
Private Async Function TestInClassAsync(code As String, expectedCode As String) As Task
Await TestAsync(
"Class C" & vbCrLf & code & vbCrLf & "End Class",
"Class C" & vbCrLf & expectedCode & vbCrLf & "End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestEmptyFile() As Task
Dim code = "$$"
Dim expected = ""
Await TestAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAtFirstPositionInFile() As Task
Dim code = "$$Class C" & vbCrLf & vbCrLf & "End Class"
Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class"
Await TestAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAtLastPositionInFile() As Task
Dim code = "Class C" & vbCrLf & vbCrLf & "End Class$$"
Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class"
Await TestAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace1() As Task
Dim code = "Dim l As New List(Of Integer) From $${}"
Dim expected = "Dim l As New List(Of Integer) From {[|}|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace2() As Task
Dim code = "Dim l As New List(Of Integer) From {$$}"
Dim expected = "Dim l As New List(Of Integer) From {[|}|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace3() As Task
Dim code = "Dim l As New List(Of Integer) From {$$ }"
Dim expected = "Dim l As New List(Of Integer) From { [|}|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace4() As Task
Dim code = "Dim l As New List(Of Integer) From { $$}"
Dim expected = "Dim l As New List(Of Integer) From [|{|] }"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace5() As Task
Dim code = "Dim l As New List(Of Integer) From { }$$"
Dim expected = "Dim l As New List(Of Integer) From [|{|] }"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace6() As Task
Dim code = "Dim l As New List(Of Integer) From {}$$"
Dim expected = "Dim l As New List(Of Integer) From [|{|]}"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen1() As Task
Dim code = "Dim l As New List$$(Of Func(Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen2() As Task
Dim code = "Dim l As New List($$Of Func(Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen3() As Task
Dim code = "Dim l As New List(Of Func$$(Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen4() As Task
Dim code = "Dim l As New List(Of Func($$Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen5() As Task
Dim code = "Dim l As New List(Of Func(Of Integer$$))"
Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen6() As Task
Dim code = "Dim l As New List(Of Func(Of Integer)$$)"
Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen7() As Task
Dim code = "Dim l As New List(Of Func(Of Integer)$$ )"
Dim expected = "Dim l As New List(Of Func[|(|]Of Integer) )"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen8() As Task
Dim code = "Dim l As New List(Of Func(Of Integer) $$)"
Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen9() As Task
Dim code = "Dim l As New List(Of Func(Of Integer) )$$"
Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen10() As Task
Dim code = "Dim l As New List(Of Func(Of Integer))$$"
Dim expected = "Dim l As New List[|(|]Of Func(Of Integer))"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket1() As Task
Dim code = "$$<Goo()> Dim i As Integer"
Dim expected = "<Goo()[|>|] Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket2() As Task
Dim code = "<$$Goo()> Dim i As Integer"
Dim expected = "<Goo()[|>|] Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket3() As Task
Dim code = "<Goo$$()> Dim i As Integer"
Dim expected = "<Goo([|)|]> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket4() As Task
Dim code = "<Goo($$)> Dim i As Integer"
Dim expected = "<Goo([|)|]> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket5() As Task
Dim code = "<Goo($$ )> Dim i As Integer"
Dim expected = "<Goo( [|)|]> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket6() As Task
Dim code = "<Goo( $$)> Dim i As Integer"
Dim expected = "<Goo[|(|] )> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket7() As Task
Dim code = "<Goo( )$$> Dim i As Integer"
Dim expected = "<Goo[|(|] )> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket8() As Task
Dim code = "<Goo()$$> Dim i As Integer"
Dim expected = "<Goo[|(|])> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket9() As Task
Dim code = "<Goo()$$ > Dim i As Integer"
Dim expected = "<Goo[|(|]) > Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket10() As Task
Dim code = "<Goo() $$> Dim i As Integer"
Dim expected = "[|<|]Goo() > Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket11() As Task
Dim code = "<Goo() >$$ Dim i As Integer"
Dim expected = "[|<|]Goo() > Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket12() As Task
Dim code = "<Goo()>$$ Dim i As Integer"
Dim expected = "[|<|]Goo()> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString1() As Task
Dim code = "Dim s As String = $$""Goo"""
Dim expected = "Dim s As String = ""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString2() As Task
Dim code = "Dim s As String = ""$$Goo"""
Dim expected = "Dim s As String = ""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString3() As Task
Dim code = "Dim s As String = ""Goo$$"""
Dim expected = "Dim s As String = [|""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString4() As Task
Dim code = "Dim s As String = ""Goo""$$"
Dim expected = "Dim s As String = [|""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString5() As Task
Dim code = "Dim s As String = ""Goo$$"
Dim expected = "Dim s As String = ""Goo"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString1() As Task
Dim code = "Dim s = $$[||]$""Goo"""
Dim expected = "Dim s = $""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString2() As Task
Dim code = "Dim s = $""$$Goo"""
Dim expected = "Dim s = $""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString3() As Task
Dim code = "Dim s = $""Goo$$"""
Dim expected = "Dim s = [|$""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString4() As Task
Dim code = "Dim s = $""Goo""$$"
Dim expected = "Dim s = [|$""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString5() As Task
Dim code = "Dim s = $"" $${x} """
Dim expected = "Dim s = $"" {x[|}|] """
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString6() As Task
Dim code = "Dim s = $"" {$$x} """
Dim expected = "Dim s = $"" {x[|}|] """
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString7() As Task
Dim code = "Dim s = $"" {x$$} """
Dim expected = "Dim s = $"" [|{|]x} """
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString8() As Task
Dim code = "Dim s = $"" {x}$$ """
Dim expected = "Dim s = $"" [|{|]x} """
Await TestInClassAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestConditionalDirectiveWithSingleMatchingDirective() As Task
Dim code =
<Text>Class C
Sub Test()
#If$$ CHK Then
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
Sub Test()
#If CHK Then
[|#End If|]
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestConditionalDirectiveWithTwoMatchingDirectives() As Task
Dim code =
<Text>Class C
Sub Test()
#If$$ CHK Then
#Else
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
Sub Test()
#If CHK Then
[|#Else|]
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestConditionalDirectiveWithAllMatchingDirectives() As Task
Dim code =
<Text>Class C
Sub Test()
#If CHK Then
#ElseIf RET Then
#Else
#End If$$
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
Sub Test()
[|#If|] CHK Then
#ElseIf RET Then
#Else
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestRegionDirective() As Task
Dim code =
<Text>Class C
$$#Region "Public Methods"
Sub Test()
End Sub
#End Region
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
#Region "Public Methods"
Sub Test()
End Sub
[|#End Region|]
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterleavedDirectivesInner() As Task
Dim code =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If CHK Then
#Region$$ "Public Methods"
Console.Write(5)
#ElseIf RET Then
Console.Write(5)
#Else
#End If
End Sub
#End Region
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If CHK Then
#Region "Public Methods"
Console.Write(5)
#ElseIf RET Then
Console.Write(5)
#Else
#End If
End Sub
[|#End Region|]
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterleavedDirectivesOuter() As Task
Dim code =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If$$ CHK Then
#Region "Public Methods"
Console.Write(5)
#ElseIf RET Then
Console.Write(5)
#Else
#End If
End Sub
#End Region
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If CHK Then
#Region "Public Methods"
Console.Write(5)
[|#ElseIf|] RET Then
Console.Write(5)
#Else
#End If
End Sub
#End Region
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedDirective1() As Task
Dim code =
<Text>Class C
$$#Region "Public Methods"
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
#Region "Public Methods"
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedDirective2() As Task
Dim code =
<Text>
#Enable Warning$$
Class C
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
#Enable Warning
Class C
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedIncompleteConditionalDirective() As Task
Dim code =
<Text>
Class C
Sub Test()
#If$$
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
Class C
Sub Test()
[|#If|]
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedCompleteConditionalDirective() As Task
Dim code =
<Text>
Class C
Sub Test()
#If$$ CHK Then
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
Class C
Sub Test()
[|#If|] CHK Then
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedConditionalDirective() As Task
Dim code =
<Text>
Class C
Sub Test()
#Else$$
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
Class C
Sub Test()
[|#Else|]
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, 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.Editor.UnitTests.BraceMatching
Imports Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces
Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.BraceMatching
Public Class VisualBasicBraceMatcherTests
Inherits AbstractBraceMatcherTests
Protected Overrides Function CreateWorkspaceFromCode(code As String, options As ParseOptions) As TestWorkspace
Return TestWorkspace.CreateVisualBasic(code)
End Function
Private Async Function TestInClassAsync(code As String, expectedCode As String) As Task
Await TestAsync(
"Class C" & vbCrLf & code & vbCrLf & "End Class",
"Class C" & vbCrLf & expectedCode & vbCrLf & "End Class")
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestEmptyFile() As Task
Dim code = "$$"
Dim expected = ""
Await TestAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAtFirstPositionInFile() As Task
Dim code = "$$Class C" & vbCrLf & vbCrLf & "End Class"
Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class"
Await TestAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAtLastPositionInFile() As Task
Dim code = "Class C" & vbCrLf & vbCrLf & "End Class$$"
Dim expected = "Class C" & vbCrLf & vbCrLf & "End Class"
Await TestAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace1() As Task
Dim code = "Dim l As New List(Of Integer) From $${}"
Dim expected = "Dim l As New List(Of Integer) From {[|}|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace2() As Task
Dim code = "Dim l As New List(Of Integer) From {$$}"
Dim expected = "Dim l As New List(Of Integer) From {[|}|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace3() As Task
Dim code = "Dim l As New List(Of Integer) From {$$ }"
Dim expected = "Dim l As New List(Of Integer) From { [|}|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace4() As Task
Dim code = "Dim l As New List(Of Integer) From { $$}"
Dim expected = "Dim l As New List(Of Integer) From [|{|] }"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace5() As Task
Dim code = "Dim l As New List(Of Integer) From { }$$"
Dim expected = "Dim l As New List(Of Integer) From [|{|] }"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestCurlyBrace6() As Task
Dim code = "Dim l As New List(Of Integer) From {}$$"
Dim expected = "Dim l As New List(Of Integer) From [|{|]}"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen1() As Task
Dim code = "Dim l As New List$$(Of Func(Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen2() As Task
Dim code = "Dim l As New List($$Of Func(Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer)[|)|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen3() As Task
Dim code = "Dim l As New List(Of Func$$(Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen4() As Task
Dim code = "Dim l As New List(Of Func($$Of Integer))"
Dim expected = "Dim l As New List(Of Func(Of Integer[|)|])"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen5() As Task
Dim code = "Dim l As New List(Of Func(Of Integer$$))"
Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen6() As Task
Dim code = "Dim l As New List(Of Func(Of Integer)$$)"
Dim expected = "Dim l As New List(Of Func[|(|]Of Integer))"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen7() As Task
Dim code = "Dim l As New List(Of Func(Of Integer)$$ )"
Dim expected = "Dim l As New List(Of Func[|(|]Of Integer) )"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen8() As Task
Dim code = "Dim l As New List(Of Func(Of Integer) $$)"
Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen9() As Task
Dim code = "Dim l As New List(Of Func(Of Integer) )$$"
Dim expected = "Dim l As New List[|(|]Of Func(Of Integer) )"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestNestedParen10() As Task
Dim code = "Dim l As New List(Of Func(Of Integer))$$"
Dim expected = "Dim l As New List[|(|]Of Func(Of Integer))"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket1() As Task
Dim code = "$$<Goo()> Dim i As Integer"
Dim expected = "<Goo()[|>|] Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket2() As Task
Dim code = "<$$Goo()> Dim i As Integer"
Dim expected = "<Goo()[|>|] Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket3() As Task
Dim code = "<Goo$$()> Dim i As Integer"
Dim expected = "<Goo([|)|]> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket4() As Task
Dim code = "<Goo($$)> Dim i As Integer"
Dim expected = "<Goo([|)|]> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket5() As Task
Dim code = "<Goo($$ )> Dim i As Integer"
Dim expected = "<Goo( [|)|]> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket6() As Task
Dim code = "<Goo( $$)> Dim i As Integer"
Dim expected = "<Goo[|(|] )> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket7() As Task
Dim code = "<Goo( )$$> Dim i As Integer"
Dim expected = "<Goo[|(|] )> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket8() As Task
Dim code = "<Goo()$$> Dim i As Integer"
Dim expected = "<Goo[|(|])> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket9() As Task
Dim code = "<Goo()$$ > Dim i As Integer"
Dim expected = "<Goo[|(|]) > Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket10() As Task
Dim code = "<Goo() $$> Dim i As Integer"
Dim expected = "[|<|]Goo() > Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket11() As Task
Dim code = "<Goo() >$$ Dim i As Integer"
Dim expected = "[|<|]Goo() > Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestAngleBracket12() As Task
Dim code = "<Goo()>$$ Dim i As Integer"
Dim expected = "[|<|]Goo()> Dim i As Integer"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString1() As Task
Dim code = "Dim s As String = $$""Goo"""
Dim expected = "Dim s As String = ""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString2() As Task
Dim code = "Dim s As String = ""$$Goo"""
Dim expected = "Dim s As String = ""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString3() As Task
Dim code = "Dim s As String = ""Goo$$"""
Dim expected = "Dim s As String = [|""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString4() As Task
Dim code = "Dim s As String = ""Goo""$$"
Dim expected = "Dim s As String = [|""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestString5() As Task
Dim code = "Dim s As String = ""Goo$$"
Dim expected = "Dim s As String = ""Goo"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString1() As Task
Dim code = "Dim s = $$[||]$""Goo"""
Dim expected = "Dim s = $""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString2() As Task
Dim code = "Dim s = $""$$Goo"""
Dim expected = "Dim s = $""Goo[|""|]"
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString3() As Task
Dim code = "Dim s = $""Goo$$"""
Dim expected = "Dim s = [|$""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString4() As Task
Dim code = "Dim s = $""Goo""$$"
Dim expected = "Dim s = [|$""|]Goo"""
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString5() As Task
Dim code = "Dim s = $"" $${x} """
Dim expected = "Dim s = $"" {x[|}|] """
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString6() As Task
Dim code = "Dim s = $"" {$$x} """
Dim expected = "Dim s = $"" {x[|}|] """
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString7() As Task
Dim code = "Dim s = $"" {x$$} """
Dim expected = "Dim s = $"" [|{|]x} """
Await TestInClassAsync(code, expected)
End Function
<Fact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterpolatedString8() As Task
Dim code = "Dim s = $"" {x}$$ """
Dim expected = "Dim s = $"" [|{|]x} """
Await TestInClassAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestConditionalDirectiveWithSingleMatchingDirective() As Task
Dim code =
<Text>Class C
Sub Test()
#If$$ CHK Then
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
Sub Test()
#If CHK Then
[|#End If|]
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestConditionalDirectiveWithTwoMatchingDirectives() As Task
Dim code =
<Text>Class C
Sub Test()
#If$$ CHK Then
#Else
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
Sub Test()
#If CHK Then
[|#Else|]
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestConditionalDirectiveWithAllMatchingDirectives() As Task
Dim code =
<Text>Class C
Sub Test()
#If CHK Then
#ElseIf RET Then
#Else
#End If$$
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
Sub Test()
[|#If|] CHK Then
#ElseIf RET Then
#Else
#End If
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestRegionDirective() As Task
Dim code =
<Text>Class C
$$#Region "Public Methods"
Sub Test()
End Sub
#End Region
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
#Region "Public Methods"
Sub Test()
End Sub
[|#End Region|]
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterleavedDirectivesInner() As Task
Dim code =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If CHK Then
#Region$$ "Public Methods"
Console.Write(5)
#ElseIf RET Then
Console.Write(5)
#Else
#End If
End Sub
#End Region
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If CHK Then
#Region "Public Methods"
Console.Write(5)
#ElseIf RET Then
Console.Write(5)
#Else
#End If
End Sub
[|#End Region|]
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestInterleavedDirectivesOuter() As Task
Dim code =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If$$ CHK Then
#Region "Public Methods"
Console.Write(5)
#ElseIf RET Then
Console.Write(5)
#Else
#End If
End Sub
#End Region
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>#Const CHK = True
Module Program
Sub Main(args As String())
#If CHK Then
#Region "Public Methods"
Console.Write(5)
[|#ElseIf|] RET Then
Console.Write(5)
#Else
#End If
End Sub
#End Region
End Module
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedDirective1() As Task
Dim code =
<Text>Class C
$$#Region "Public Methods"
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>Class C
#Region "Public Methods"
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7120, "https://github.com/dotnet/roslyn/issues/7120")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedDirective2() As Task
Dim code =
<Text>
#Enable Warning$$
Class C
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
#Enable Warning
Class C
Sub Test()
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedIncompleteConditionalDirective() As Task
Dim code =
<Text>
Class C
Sub Test()
#If$$
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
Class C
Sub Test()
[|#If|]
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedCompleteConditionalDirective() As Task
Dim code =
<Text>
Class C
Sub Test()
#If$$ CHK Then
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
Class C
Sub Test()
[|#If|] CHK Then
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
<WorkItem(7534, "https://github.com/dotnet/roslyn/issues/7534")>
<WpfFact, Trait(Traits.Feature, Traits.Features.BraceMatching)>
Public Async Function TestUnmatchedConditionalDirective() As Task
Dim code =
<Text>
Class C
Sub Test()
#Else$$
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Dim expected =
<Text>
Class C
Sub Test()
[|#Else|]
End Sub
End Class
</Text>.Value.Replace(vbLf, vbCrLf)
Await TestAsync(code, expected)
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/CSharp/Test/Symbol/Compilation/TypeInfoTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class TypeInfoTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var c = CreateCompilation("");
var obj = c.GetSpecialType(SpecialType.System_Object).GetPublicSymbol();
var int32 = c.GetSpecialType(SpecialType.System_Int32).GetPublicSymbol();
var notNullable = new NullabilityInfo(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableFlowState.NotNull);
var nullable = new NullabilityInfo(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableFlowState.MaybeNull);
EqualityTesting.AssertEqual(default(TypeInfo), default(TypeInfo));
EqualityTesting.AssertEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32, nullable, notNullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32, nullable, notNullable));
EqualityTesting.AssertNotEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable));
EqualityTesting.AssertNotEqual(new TypeInfo(int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable));
EqualityTesting.AssertNotEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.NotAnnotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), notNullable, nullable));
EqualityTesting.AssertNotEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32, nullable, notNullable));
EqualityTesting.AssertEqual(new TypeInfo(int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default),
new TypeInfo(int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default));
var intEnum1 = c.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).GetPublicSymbol().Construct(int32);
var intEnum2 = c.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).GetPublicSymbol().Construct(int32);
EqualityTesting.AssertEqual(new TypeInfo(intEnum1.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default),
new TypeInfo(intEnum2.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp
{
public class TypeInfoTests : CSharpTestBase
{
[Fact]
public void Equality()
{
var c = CreateCompilation("");
var obj = c.GetSpecialType(SpecialType.System_Object).GetPublicSymbol();
var int32 = c.GetSpecialType(SpecialType.System_Int32).GetPublicSymbol();
var notNullable = new NullabilityInfo(CodeAnalysis.NullableAnnotation.NotAnnotated, CodeAnalysis.NullableFlowState.NotNull);
var nullable = new NullabilityInfo(CodeAnalysis.NullableAnnotation.Annotated, CodeAnalysis.NullableFlowState.MaybeNull);
EqualityTesting.AssertEqual(default(TypeInfo), default(TypeInfo));
EqualityTesting.AssertEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32, nullable, notNullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32, nullable, notNullable));
EqualityTesting.AssertNotEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable));
EqualityTesting.AssertNotEqual(new TypeInfo(int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable));
EqualityTesting.AssertNotEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.NotAnnotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), notNullable, nullable));
EqualityTesting.AssertNotEqual(new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), nullable, nullable),
new TypeInfo(obj.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.Annotated), int32, nullable, notNullable));
EqualityTesting.AssertEqual(new TypeInfo(int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default),
new TypeInfo(int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default));
var intEnum1 = c.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).GetPublicSymbol().Construct(int32);
var intEnum2 = c.GetSpecialType(SpecialType.System_Collections_Generic_IEnumerable_T).GetPublicSymbol().Construct(int32);
EqualityTesting.AssertEqual(new TypeInfo(intEnum1.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default),
new TypeInfo(intEnum2.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), int32.WithNullableAnnotation(CodeAnalysis.NullableAnnotation.None), default, default));
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Scripting/CoreTestUtilities/TestCompilationFactory.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Scripting
{
internal static class TestCompilationFactory
{
// TODO: we need to clean up and refactor CreateCompilationWithMscorlib in compiler tests
// so that it can be used in portable tests.
internal static Compilation CreateCSharpCompilationWithCorlib(string source, string assemblyName = null)
{
return CSharpCompilation.Create(
assemblyName ?? Guid.NewGuid().ToString(),
new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) },
new[] { TestReferences.NetStandard13.SystemRuntime },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
internal static Compilation CreateVisualBasicCompilationWithCorlib(string source, string assemblyName = null)
{
return VisualBasicCompilation.Create(
assemblyName ?? Guid.NewGuid().ToString(),
new[] { VisualBasic.SyntaxFactory.ParseSyntaxTree(source) },
new[] { TestReferences.NetStandard13.SystemRuntime },
new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
internal static Compilation CreateCSharpCompilation(string source, IEnumerable<MetadataReference> references, string assemblyName = null, CSharpCompilationOptions options = null)
{
return CSharpCompilation.Create(
assemblyName ?? Guid.NewGuid().ToString(),
new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) },
references,
options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.VisualBasic;
namespace Microsoft.CodeAnalysis.Scripting
{
internal static class TestCompilationFactory
{
// TODO: we need to clean up and refactor CreateCompilationWithMscorlib in compiler tests
// so that it can be used in portable tests.
internal static Compilation CreateCSharpCompilationWithCorlib(string source, string assemblyName = null)
{
return CSharpCompilation.Create(
assemblyName ?? Guid.NewGuid().ToString(),
new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) },
new[] { TestReferences.NetStandard13.SystemRuntime },
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
internal static Compilation CreateVisualBasicCompilationWithCorlib(string source, string assemblyName = null)
{
return VisualBasicCompilation.Create(
assemblyName ?? Guid.NewGuid().ToString(),
new[] { VisualBasic.SyntaxFactory.ParseSyntaxTree(source) },
new[] { TestReferences.NetStandard13.SystemRuntime },
new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
internal static Compilation CreateCSharpCompilation(string source, IEnumerable<MetadataReference> references, string assemblyName = null, CSharpCompilationOptions options = null)
{
return CSharpCompilation.Create(
assemblyName ?? Guid.NewGuid().ToString(),
new[] { CSharp.SyntaxFactory.ParseSyntaxTree(source) },
references,
options ?? new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));
}
}
}
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/VisualBasic/Portable/Syntax/VisualBasicSyntaxVisitor.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>
''' Represents a <see cref="SyntaxNode"/> visitor that visits only the single SyntaxNode
''' passed into its <see cref="Visit(SyntaxNode)"/> method.
''' </summary>
Partial Public MustInherit Class VisualBasicSyntaxVisitor
Public Overridable Sub Visit(ByVal node As SyntaxNode)
If node IsNot Nothing Then
DirectCast(node, VisualBasicSyntaxNode).Accept(Me)
End If
End Sub
Public Overridable Sub DefaultVisit(ByVal node As SyntaxNode)
End Sub
End Class
''' <summary>
''' Represents a <see cref="SyntaxNode"/> visitor that visits only the single SyntaxNode
''' passed into its <see cref="Visit(SyntaxNode)"/> method and produces
''' a value of the type specified by the <typeparamref name="TResult"/> parameter.
''' </summary>
''' <typeparam name="TResult">
''' The type of the return value of this visitor's Visit method.
''' </typeparam>
Partial Public MustInherit Class VisualBasicSyntaxVisitor(Of TResult)
Public Overridable Function Visit(ByVal node As SyntaxNode) As TResult
If node IsNot Nothing Then
Return DirectCast(node, VisualBasicSyntaxNode).Accept(Me)
End If
Return Nothing
End Function
Public Overridable Function DefaultVisit(ByVal node As SyntaxNode) As TResult
Return Nothing
End Function
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
''' <summary>
''' Represents a <see cref="SyntaxNode"/> visitor that visits only the single SyntaxNode
''' passed into its <see cref="Visit(SyntaxNode)"/> method.
''' </summary>
Partial Public MustInherit Class VisualBasicSyntaxVisitor
Public Overridable Sub Visit(ByVal node As SyntaxNode)
If node IsNot Nothing Then
DirectCast(node, VisualBasicSyntaxNode).Accept(Me)
End If
End Sub
Public Overridable Sub DefaultVisit(ByVal node As SyntaxNode)
End Sub
End Class
''' <summary>
''' Represents a <see cref="SyntaxNode"/> visitor that visits only the single SyntaxNode
''' passed into its <see cref="Visit(SyntaxNode)"/> method and produces
''' a value of the type specified by the <typeparamref name="TResult"/> parameter.
''' </summary>
''' <typeparam name="TResult">
''' The type of the return value of this visitor's Visit method.
''' </typeparam>
Partial Public MustInherit Class VisualBasicSyntaxVisitor(Of TResult)
Public Overridable Function Visit(ByVal node As SyntaxNode) As TResult
If node IsNot Nothing Then
Return DirectCast(node, VisualBasicSyntaxNode).Accept(Me)
End If
Return Nothing
End Function
Public Overridable Function DefaultVisit(ByVal node As SyntaxNode) As TResult
Return Nothing
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/VisualBasic/Extensions/SingleLineRewriter.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.Text.RegularExpressions
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Class SingleLineRewriter
Inherits VisualBasicSyntaxRewriter
Private Shared ReadOnly s_newlinePattern As Regex = New Regex("[\r\n]+")
Private ReadOnly _useElasticTrivia As Boolean
Private _lastTokenEndedInWhitespace As Boolean
Public Sub New(Optional useElasticTrivia As Boolean = False)
_useElasticTrivia = useElasticTrivia
End Sub
Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
If _lastTokenEndedInWhitespace Then
token = token.WithLeadingTrivia(Enumerable.Empty(Of SyntaxTrivia)())
ElseIf token.LeadingTrivia.Count > 0 Then
If _useElasticTrivia Then
token = token.WithLeadingTrivia(SyntaxFactory.ElasticSpace)
Else
token = token.WithLeadingTrivia(SyntaxFactory.Space)
End If
End If
If token.TrailingTrivia.Count > 0 Then
If _useElasticTrivia Then
token = token.WithTrailingTrivia(SyntaxFactory.ElasticSpace)
Else
token = token.WithTrailingTrivia(SyntaxFactory.Space)
End If
_lastTokenEndedInWhitespace = True
Else
_lastTokenEndedInWhitespace = False
End If
If token.Kind() = SyntaxKind.StringLiteralToken OrElse
token.Kind() = SyntaxKind.InterpolatedStringTextToken Then
If s_newlinePattern.IsMatch(token.Text) Then
Dim newText = s_newlinePattern.Replace(token.Text, " ")
If token.Kind() = SyntaxKind.StringLiteralToken Then
token = SyntaxFactory.StringLiteralToken(
token.LeadingTrivia,
newText, newText,
token.TrailingTrivia)
Else
token = SyntaxFactory.InterpolatedStringTextToken(
token.LeadingTrivia,
newText, newText,
token.TrailingTrivia)
End If
End If
End If
Return token
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.Text.RegularExpressions
Namespace Microsoft.CodeAnalysis.VisualBasic.Extensions
Friend Class SingleLineRewriter
Inherits VisualBasicSyntaxRewriter
Private Shared ReadOnly s_newlinePattern As Regex = New Regex("[\r\n]+")
Private ReadOnly _useElasticTrivia As Boolean
Private _lastTokenEndedInWhitespace As Boolean
Public Sub New(Optional useElasticTrivia As Boolean = False)
_useElasticTrivia = useElasticTrivia
End Sub
Public Overrides Function VisitToken(token As SyntaxToken) As SyntaxToken
If _lastTokenEndedInWhitespace Then
token = token.WithLeadingTrivia(Enumerable.Empty(Of SyntaxTrivia)())
ElseIf token.LeadingTrivia.Count > 0 Then
If _useElasticTrivia Then
token = token.WithLeadingTrivia(SyntaxFactory.ElasticSpace)
Else
token = token.WithLeadingTrivia(SyntaxFactory.Space)
End If
End If
If token.TrailingTrivia.Count > 0 Then
If _useElasticTrivia Then
token = token.WithTrailingTrivia(SyntaxFactory.ElasticSpace)
Else
token = token.WithTrailingTrivia(SyntaxFactory.Space)
End If
_lastTokenEndedInWhitespace = True
Else
_lastTokenEndedInWhitespace = False
End If
If token.Kind() = SyntaxKind.StringLiteralToken OrElse
token.Kind() = SyntaxKind.InterpolatedStringTextToken Then
If s_newlinePattern.IsMatch(token.Text) Then
Dim newText = s_newlinePattern.Replace(token.Text, " ")
If token.Kind() = SyntaxKind.StringLiteralToken Then
token = SyntaxFactory.StringLiteralToken(
token.LeadingTrivia,
newText, newText,
token.TrailingTrivia)
Else
token = SyntaxFactory.InterpolatedStringTextToken(
token.LeadingTrivia,
newText, newText,
token.TrailingTrivia)
End If
End If
End If
Return token
End Function
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Compilers/VisualBasic/Portable/BoundTree/BoundNamespaceExpression.vb | ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundNamespaceExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol, hasErrors As Boolean)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol)
End Sub
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return If(DirectCast(Me.AliasOpt, Symbol), Me.NamespaceSymbol)
End Get
End Property
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
If NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then
Return LookupResult.WorseResultKind(LookupResultKind.Ambiguous, MyBase.ResultKind)
End If
Return MyBase.ResultKind
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(UnevaluatedReceiverOpt Is Nothing OrElse UnevaluatedReceiverOpt.Kind = BoundKind.NamespaceExpression)
Debug.Assert(AliasOpt Is Nothing OrElse NamespaceSymbol.NamespaceKind <> NamespaceKindNamespaceGroup)
End Sub
#End If
End Class
End Namespace
| ' Licensed to the .NET Foundation under one or more agreements.
' The .NET Foundation licenses this file to you under the MIT license.
' See the LICENSE file in the project root for more information.
Imports Microsoft.CodeAnalysis.Text
Imports Microsoft.CodeAnalysis.VisualBasic.Symbols
Imports Microsoft.CodeAnalysis.VisualBasic.Syntax
Namespace Microsoft.CodeAnalysis.VisualBasic
Partial Friend Class BoundNamespaceExpression
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol, hasErrors As Boolean)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol, hasErrors)
End Sub
Public Sub New(syntax As SyntaxNode, unevaluatedReceiverOpt As BoundExpression, namespaceSymbol As NamespaceSymbol)
MyClass.New(syntax, unevaluatedReceiverOpt, Nothing, namespaceSymbol)
End Sub
Public Overrides ReadOnly Property ExpressionSymbol As Symbol
Get
Return If(DirectCast(Me.AliasOpt, Symbol), Me.NamespaceSymbol)
End Get
End Property
Public Overrides ReadOnly Property ResultKind As LookupResultKind
Get
If NamespaceSymbol.NamespaceKind = NamespaceKindNamespaceGroup Then
Return LookupResult.WorseResultKind(LookupResultKind.Ambiguous, MyBase.ResultKind)
End If
Return MyBase.ResultKind
End Get
End Property
#If DEBUG Then
Private Sub Validate()
Debug.Assert(UnevaluatedReceiverOpt Is Nothing OrElse UnevaluatedReceiverOpt.Kind = BoundKind.NamespaceExpression)
Debug.Assert(AliasOpt Is Nothing OrElse NamespaceSymbol.NamespaceKind <> NamespaceKindNamespaceGroup)
End Sub
#End If
End Class
End Namespace
| -1 |
|
dotnet/roslyn | 56,084 | remove WaitAndGetResult from Preview generation code. | CyrusNajmabadi | "2021-09-01T20:07:21Z" | "2021-09-01T21:16:27Z" | 02ff8fa26bdaa72deef6dc9d7281b8bf2f11286a | 6bd477f7711065f846c3be2c1e726467f24f70e8 | remove WaitAndGetResult from Preview generation code.. | ./src/Workspaces/Core/Portable/Workspace/Host/TaskScheduler/WorkspaceAsynchronousOperationListenerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceService(typeof(IWorkspaceAsynchronousOperationListenerProvider), ServiceLayer.Default)]
[Shared]
internal sealed class WorkspaceAsynchronousOperationListenerProvider : IWorkspaceAsynchronousOperationListenerProvider
{
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public WorkspaceAsynchronousOperationListenerProvider(IAsynchronousOperationListenerProvider listenerProvider)
=> _listener = listenerProvider.GetListener(FeatureAttribute.Workspace);
public IAsynchronousOperationListener GetListener()
=> _listener;
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using System;
using System.Composition;
namespace Microsoft.CodeAnalysis.Host
{
[ExportWorkspaceService(typeof(IWorkspaceAsynchronousOperationListenerProvider), ServiceLayer.Default)]
[Shared]
internal sealed class WorkspaceAsynchronousOperationListenerProvider : IWorkspaceAsynchronousOperationListenerProvider
{
private readonly IAsynchronousOperationListener _listener;
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public WorkspaceAsynchronousOperationListenerProvider(IAsynchronousOperationListenerProvider listenerProvider)
=> _listener = listenerProvider.GetListener(FeatureAttribute.Workspace);
public IAsynchronousOperationListener GetListener()
=> _listener;
}
}
| -1 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.